.NET - How do I retrieve specific items out of a Dataset?

后端 未结 5 2046
天命终不由人
天命终不由人 2021-02-07 18:50

I have the following code which connects to a database and stores the data into a dataset.

What I need to do now is get a single value from the data set (well actually i

相关标签:
5条回答
  • 2021-02-07 19:27
    int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
    int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
    
    0 讨论(0)
  • 2021-02-07 19:29
    int intVar = (int)ds.Tables[0].Rows[0][n];   // n = column index
    
    0 讨论(0)
  • 2021-02-07 19:36

    You can do like...

    If you want to access using ColumnName

    Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
    Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());
    

    OR, if you want to access using Index

    Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
    Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());
    
    0 讨论(0)
  • 2021-02-07 19:36

    I prefer to use something like this:

    int? var1 = ds.Tables[0].Rows[0].Field<int?>("ColumnName");
    

    or

    int? var1 = ds.Tables[0].Rows[0].Field<int?>(3);   //column index
    
    0 讨论(0)
  • 2021-02-07 19:40

    The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

    int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());
    

    and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

    int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());
    
    0 讨论(0)
提交回复
热议问题