从一个单词搜索和无法访问的代码返回整个字符串

时间:2018-10-27 10:21:16

标签: c# winforms search datagridview

此代码有问题。它仅返回字符串中的第一个单词。如果有人输入一个或两个单词,并且只输入字符串中的某些字符,则需要Column中返回的整个字符串。

从头一个TextBox DataGridView开始的Column中进行搜索。这是一个存储在XML文件中的收集列表,该文件已加载到DataGridView

我还在i++中有一个for (int i = 0; i < row.Cells.Count; i++),指出它无法访问。
我也不知道为什么。

这只是一个绑定列表作为集合。

Picture of WinForms App

//Search DataGridview Button 
private void button3_Click(object sender, EventArgs e)
{
    string searchValue = searchtextBox.Text.ToLower(); /
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    try 
    {
        bool valueResult = false;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            for (int i = 0; i < row.Cells.Count; i++)
            {
                //if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().ToLower().Equals(searchValue))
                if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().ToLower().Contains(searchValue))
                {
                    int rowIndex = row.Index;
                    dataGridView1.Rows[rowIndex].Selected = true;
                    valueResult = true;
                    searchResults.Text += "=> " + searchValue + " " + Environment.NewLine.Trim();
                }
                break;         
            }
        }

        if (!valueResult)
        {
            MessageBox.Show("Unable to find " + searchtextBox.Text, "Not Found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            return;
        }
    }
    catch (Exception exc)box
    {
        MessageBox.Show(exc.Message);
    }         
}

1 个答案:

答案 0 :(得分:1)

删除了中断并修复了i++上的隐藏代码,并删除了searchValue并替换为row.Cells[0].Value
我认为这是searchValue和中断问题。

感谢大家澄清问题。

//Search DataGridview Button 
private void button3_Click(object sender, EventArgs e)
{
    string searchValue = searchtextBox.Text.ToLower(); //simple search Full row from text box with button
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

    try //try to run the following code
    {
        bool valueResult = false;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            //i++
            for (int i = 0; i < row.Cells.Count; i++)//for loop to enable iteration throught the gridview rows
            {
                //if (row.Cells[0].Value != null && row.Cells[0].Value.ToString().ToLower().Equals(searchValue))

                if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().ToLower().Contains(searchValue))
                {
                    int rowIndex = row.Index;
                    dataGridView1.Rows[rowIndex].Selected = true;
                    valueResult = true;

                    searchResults.Text += "=> " + row.Cells[i].Value + " " + Environment.NewLine.Trim();//outputs search results to multi line textbox separated by commas and trimmed white space of   
                }
            }
        }
    }
}