简体   繁体   中英

How can I get value of a specific cell in DataTable in c#?

I am new to c# and using windows forms.

屏幕截图

I have a dataTable as shown in screenshot, I want to get a value of specific cell in button_Text column based on Button_Name column value and save it in a string. I know I can use this code :

string s = DataTable.Rows[2][1];

But I do not want to use it because I do not want to use numbers between brackets to index the cell value but instead I want to use the a Button_Name column value and button_Text column name to index the cell value. For example:

string s = DataTable.Rows[ButtonUC1_3][Button_Text]; // but it gives error : "Argument1: can not convert from string to int"

I hope it is clear enough. Anyone knows how to achieve this? Thank you

Use LINQ to DataSet there you can use column names

string value = dataTable.AsEnumerable()
               .Where((row) => row.Field<string>("button_Name").Equals("ButtonUC_1"))
               .Select((row) => row.Field<string>("button_Text"))
               .FirstOrDefault();

Here Rows Must be Int formet,But Columns string allowed, below one is error

string s = DataTable.Rows["ButtonUC1_3"]["Button_Text"]; 

the correct formet is,

string s = DataTable.Rows[2]["Button_Text"]; 

It will give the cell value,.

DataTable Rows don't have names, they're indexed only by number. If you want to access the rows through the names you specified, you need to use your own mapping, eg var rowMapping = new Dictionary<string,int>() { { ButtonUC1_3, 0}, ... } and then access the DataTable like this DataTable.Rows[rowMapping[ButtonUC1_3]][Button_Text] .

Obviously, this is not the only way how to do it, you could define an enum, integer constants, etc. It all depends how many rows you have and how you use your DataTable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM