سؤال

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

هل كانت مفيدة؟

المحلول

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"]

نصائح أخرى

Try this

int Contract_id = Convert.ToInt32(dsDiscounts.Tables[1].Rows[0]["CONTACT_ID"]);
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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top