winforms 在DataGridView中的列中搜索值

t3irkdon  于 2022-11-17  发布在  其他
关注(0)|答案(9)|浏览(253)

我希望用户能够在DataGridView(dgv)的列中搜索编号。dgv可以包含许多记录。每个记录都有一个项目编号。因此,我希望用户能够在“项目编号”列中搜索项目编号。我拥有的列有:项目ID(不可见);图像(无标题文本);项目编号:项目名称:公司;联系人。
下面是我的代码:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;
    int rowIndex = -1;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dgvProjects.Rows[row.Index].Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}

**问题#1:**目前为止的功能:使用者在TextBox 1中输入项目编号。当他/她按一下按钮时,程式码会在数据列中搜寻这个字串,当找到项目编号时,就会选取该数据列。它可以正常运作,但只有一次。当我想要搜寻其他项目编号时,却没有任何React。
**问题#2:**我认为可以用更好的方法来完成,即只搜索“项目名称”列的值。但是我应该如何正确地执行此操作呢?

我用来搜索的代码来自this answer

7fyelxc5

7fyelxc51#

为什么要使用row.Cells[row.Index]。需要指定要搜索的列的索引(问题2)。例如,需要将row.Cells[row.Index]更改为row.Cells[2],其中2是列的索引:

private void btnSearch_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

    dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        foreach (DataGridViewRow row in dgvProjects.Rows)
        {
            if (row.Cells[2].Value.ToString().Equals(searchValue))
            {
                row.Selected = true;
                break;
            }
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}
owfi6suc

owfi6suc2#

为什么不先构建一个DataTable,然后将其作为DataSource分配给DataGridView

DataTable table4DataSource=new DataTable();

table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");

...

(add您的行,手动,在一个圆圈中或通过数据库表中的DataReader)(分配数据源)

dtGrdViewGrid.DataSource = table4DataSource;

然后用途:

(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();

您甚至可以将这段代码放在您的textbox_textchange事件中,您的过滤值将在您编写时显示。

hwazgwia

hwazgwia3#

最好将逻辑分离到另一个方法中,或者另一个类中。
此方法将帮助您检索在其中找到文本的DataGridViewCell对象。

/// <summary>
    /// Check if a given text exists in the given DataGridView at a given column index
    /// </summary>
    /// <param name="searchText"></param>
    /// <param name="dataGridView"></param>
    /// <param name="columnIndex"></param>
    /// <returns>The cell in which the searchText was found</returns>
    private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
    {
        DataGridViewCell cellWhereTextIsMet = null;

        // For every row in the grid (obviously)
        foreach (DataGridViewRow row in dataGridView.Rows)
        {
            // I did not test this case, but cell.Value is an object, and objects can be null
            // So check if the cell is null before using .ToString()
            if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
            {
                // the searchText is equals to the text in this cell.
                cellWhereTextIsMet = row.Cells[columnIndex];
                break;
            }
        }

        return cellWhereTextIsMet;
    }

    private void button_click(object sender, EventArgs e)
    {
        DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
        if (cell != null)
        {
            // Value exists in the grid
            // you can do extra stuff on the cell
            cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
        }
        else
        {
            // Value does not exist in the grid
        }
    }
nwlqm0z1

nwlqm0z14#

//     This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
    string searchValue=textBoxSearch.Text;
    int rowIndex = 1;  //this one is depending on the position of cell or column
    //string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;

    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    try
    {
        bool valueResulet = true;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
            {
                rowIndex = row.Index;
                dataGridView1.Rows[rowIndex].Selected = true;
                rowIndex++;
                valueResulet = false;
            }
        }
        if (valueResulet != false)
        {
            MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
            return;
        }
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message);
    }
}
yzuktlbb

yzuktlbb5#

直接从DataTableDataset筛选数据:

"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
   this.dataGridView1.DataSource = "MyTable".DefaultView;

Textbox的事件KeyUp上使用此代码,将“MyTable”替换为表名或数据集,将“MyTable”替换为要进行搜索的字段。

icomxhvb

icomxhvb6#

“我的表”。默认视图。行筛选器=“LIKE '%”+文本框1.Text+“%'”;数据源=“我的表”.默认视图;
数据库连接和数据表的关系如何?我应该如何正确设置DefaultView?
我用下面的代码来获取数据:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();
i2byvkas

i2byvkas7#

private void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            string searchValue = txtSearch.Text;
            string colName = dataGridView1.Columns[1].Name;//Column Number of Search
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
      
    }

    private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        btnSearch_Click(null,null);
    }
nkkqxpd9

nkkqxpd98#

private void txtSearch_TextChanged(object sender, EventArgs e)
{
     string searchValue = txtSearch.Text;
     for (var i = 0; i <= dgvList.RowCount; i++)
     {
          for (var j = 0; j <= dgvList.ColumnCount; j++)
          {
               if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
               {
                    Console.Writeline("found");
                    dgvList.Item(j, i).Selected = true;
                    return;
               }
          }
     }
     
}

此方法将搜索DataGridView中的所有行和单元格,如果结果为true,则选择该行。

cygmwpex

cygmwpex9#

我很可以简单地解决它:

public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
    {
        foreach (DataGridViewRow Row in dgv.Rows)
        {
            if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
                return Row.Index;
        }
        return -1;
    }

相关问题