Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c# - Why is DataRow not found in DataTable

New to data manipulation using DataTable, DataColumn, DataRow. Why is employee not found in the DataTable? I was expected indexFound to have the value "2", and when I debug the values all look correct.

// Manually create a new DataTable
DataTable dtEmployees = new DataTable("Employee");

// Add columns
dtEmployees.Columns.Add("ID", typeof(int));
dtEmployees.Columns.Add("Name", typeof(string));
dtEmployees.Columns.Add("Salary", typeof(int));

// Add rows to the table
dtEmployees.Rows.Add(52, "Sally", 29000);
dtEmployees.Rows.Add(63, "Harry", 22000);
dtEmployees.Rows.Add(72, "Alain", 23000);
dtEmployees.Rows.Add(110, "Pete", 24500);

// Look for an employee...
int index = 2;
Console.WriteLine("(index of DataRow({0}) should return {0})", index);
DataRow employee = dtEmployees.NewRow();
employee["ID"] = dtEmployees.Rows[index]["ID"];
employee["Name"] = dtEmployees.Rows[index]["Name"];
employee["Salary"] = dtEmployees.Rows[index]["Salary"];

int indexFound = dtEmployees.Rows.IndexOf(employee);
if (indexFound != -1)
    Console.Write("  Employee has index {0}", indexFound); // Was expecting this...
else
    Console.Write("  Employee not found in table..."); // ...but actually get this. Why??

The Microsoft documentation didn't provide any meaningful help.

question from:https://stackoverflow.com/questions/65944204/why-is-datarow-not-found-in-datatable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A DataRow needs to be added to the Rows collection of the Datatable if you want to find it in the collection with IndexOf, so you just need to add this line before searching the row

dtEmployees.Rows.Add(employee);

Of course this method (IndexOf) is of some value only if you have a row to search for. Usually if you want to search a Datatable the preferred way is through the Select method that could return a set of one or more rows using a search criteria that resembles a WHERE sql statement.

dtEmployees.Rows.Add(employee);
DataRow[] rows = dtEmployees.Select("ID = 72");
if(rows != null && rows.Length > 0)
{
     Console.WriteLine("rows found:" + rows.Length);
     foreach(DataRow r in rows)
        Console.WriteLine(r.Field<string>("name"));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...