Save dataset value as an integer
I have a dataset that has just one column and one row. It gives me an inte开发者_运维百科ger. I have to save it in an other integer. I am a learner. please help me out! Thanks!
Dataset pds;
if (pds.Tables[0].Rows.Count > 0)
{
int Islocationcount = pds.Tables[0].Columns[0].ColumnName[1];
}
You want
int Islocationcount = Convert.ToInt32(pds.Tables[0].Rows[1][0]);
assuming it won't be DBNull.Value
, otherwise it will throw an exception
.NET has some functionality that can help. Check out:
System.Convert
int.TryParse
Also, make sure you properly check if the value coming out of the column is equal to DBNull.Value, that's a common source of runtime errors for new .NET developers doing this.
int value = (int)pds.Tables[0].Rows[0]["ColumnName"]; //or can use column index 0
You may want to check a few things here with this kind of stuff. I usually check to make sure the Dataset
is not null, then make sure it has at least one table and one row. If it does have all those things, then double check that the value you're looking for is not null and is an actual integer. Here is an example (VB.NET because I'm familiar):
Dim IsLocationCounter As Integer
If (Not pds Is Nothing AndAlso pds.Tables.Count > 0 AndAlso pds.Tables[0].Rows.Count > 0) Then
/* I can't remember here if you can use <> or if you have to use Is */
If (pds.Tables[0].Columns[0].ColumnName[1] <> DBValue.Null) Then
/* Because you pass an integer by reference to TryParse, you don't have to set anything in an else statement */
If ( Not Integer.TryParse(pds.Tables[0].Columns[0].ColumnName[1].ToString(), IsLocationcounter) ) Then
Throw New Exception ("Do some error handling here because there is no int coming back in your dataset")
End If
End If
End If
Just as a note for the example that you have in your question, you won't be able to use that IsLocationCount
variable outside of that If
statement if you declare it inside the If
statement. If you need it outside of the If
statement you should declare it outside of it.
Dim value As integer = ds.Tables(0).Rows(0)(0)
精彩评论