在DataGridView中查找数据

本文关键字:数据 查找 DataGridView | 更新日期: 2023-09-27 18:18:28

我正试图使一个程序,在一个DataGridView在一个文本框中引入的文本搜索。我一直工作到某一点。我想在另一个文本框中写入它找到的值,但它所做的就是在该文本框中写入"-1"。为什么?是我遗漏了什么还是我做错了什么?

下面是我的代码:
    private void PopulateDataViewAndFind()
    {
        DataSet set1 = new DataSet();
        string sourceXml = "<?xml version='1.0' encoding='UTF-8'?>" +
        "<music>" +
        "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd></recording>" +
        "<recording><artist>Dave Matthews</artist><cd>Under the Table and Dreaming</cd></recording>" +
        "<recording><artist>Natalie Merchant</artist><cd>Tigerlily</cd></recording>" +
        "<recording><artist>U2</artist><cd>How to Dismantle an Atomic Bomb</cd></recording>" +
        "</music>";
        StringReader reader = new StringReader(sourceXml);
        set1.ReadXml(reader);
        DataTableCollection tables = set1.Tables;
        DataView view1 = new DataView(tables[0]);
        BindingSource source1 = new BindingSource();
        source1.DataSource = view1;
        dataGridView1.DataSource = source1;
        int itemFound = source1.Find("artist", textBox1.Text);
        source1.Position = itemFound;
        string cdFound = source1.Find("cd", textBox1.Text).ToString();
        textBox2.Text = cdFound;
    }

请帮忙,谢谢!:)

在DataGridView中查找数据

Replace:

string cdFound = source1.Find("cd", textBox1.Text).ToString();

:

string cdFound = ((DataRowView)source1.Current).Row["cd"].ToString();