Wednesday, March 21, 2012

DataRow syntax

command.CommandText = "SELECT UserName from Users WHERE UserID = " = userID

Executing this command returns one table with one column with one row. What is the syntax for getting that value into a variable? I can get the information into a dataSet but I can't get it out. Should I be using a dataSet for this operation?

The rest of the code so far:

SqlDataAdapter dataAdapter =newSqlDataAdapter();

dataAdapter.SelectCommand = command;

dataAdapter.TableMappings.Add("Table","Users");

dataSet =newDataSet();

dataAdapter.Fill(dataSet);

Using that code, your data would be in dataSet.tables[0].rows[0][0].

If that's always just returning one value, you might want to look into using ExecuteScalar instead of the adapter and dataset.

|||

You can just use executeScalar method of SQl command below is example from VB.Net help for scalar modified a little:

Public Function AddProductCategory( _ ByVal UserID As Integer, ByVal connString As String) As Integer Dim Username As string = "" Dim sql As String = "SELECT UserName from Users WHERE UserID = @.USERID" Using conn As New SqlConnection(connString) Dim cmd As New SqlCommand(sql, conn) cmd.Parameters.Add("@.USERID", SqlDbType.Int) cmd.Parameters("@.USERID").Value = newName Try conn.Open() userName = Convert.ToInt32(cmd.ExecuteScalar()) Catch ex As Exception Console.WriteLine(ex.Message) End Try End Using Return newProdIDEnd Function
Thanks
|||

Got it working ... thank you for your help!