Reputation: 945
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
Upvotes: 1
Views: 5305
Reputation: 32445
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();
Upvotes: 3
Reputation: 635
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,.
Upvotes: 0
Reputation: 44
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, e.g. 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.
Upvotes: -1