DannyDSB DannyDSB - 18 days ago 9
C# Question

Find Data in DataGridView - C#

I am trying to make a program that searches in a DataGridView a text introduced in a TextBox. Id works until a certain point.
I want to write in another TextBox the value that it have found, but all it does is to write in that TextBox "-1". Why? Am I missing something or I am doing something wrong?

Here is my code:

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;
}


Please help, thanks! :)

Answer

Replace:

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

to:

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