Reputation: 524
I have a dataset with two tables.I want to get the value of first column from second table and initialize it to an int variable.
The name of that column was CONTACT_ID
I tried like this.
int Contract_id = Convert.ToInt32(dsDiscounts.Tables[1].Columns[0]);
but it was showing an error:
Unable to cast object of type 'System.Data.DataColumn' to type 'System.IConvertible'.
can anyone help me please
Upvotes: 15
Views: 95565
Reputation: 1
public static T SafeGet<T>(this System.Data.DataSet dataset, string tableindex, int RowCount, string Nameofcolumn)
{
try
{
return dataset.Tables[tableindex].Rows[RowCount].IsNull(Nameofcolumn) == false ?
(T)Convert.ChangeType(dataset.Tables[tableindex].Rows[RowCount][Nameofcolumn], typeof(T))
: default(T);
}
catch (Exception ex)
{
throw ex;
}
}
Upvotes: 0
Reputation: 236308
dsDiscounts.Tables[1].Columns[0]
returns column definition (data type, caption, etc defined by DataColumn instance). Of course column definition conversion to integer fails.
What you need is cell value from some row of table (assume first row). You should use Rows
collection to get access to table rows. After you get required DataRow
by it's index, you can access cells in row by index, column name, column object, etc. E.g. getting first row's cell value by column name:
dsDiscounts.Tables[1].Rows[0]["CONTACT_ID"]
Upvotes: 38
Reputation: 40990
Try this
int Contract_id = Convert.ToInt32(dsDiscounts.Tables[1].Rows[0]["CONTACT_ID"]);
Upvotes: 3