Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieving data from sql database using C# with stored procedure

Whenever I try to retrieve data from my database i keep getting null. The code i'm using is below:

protected void Button2_Click(object sender, EventArgs e)
 {
    SqlConnection myConnection = new SqlConnection(GetConnectionString());
    SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection);
    cmd.CommandType = CommandType.StoredProcedure;
    myConnection.Open();

    SqlParameter custId = cmd.Parameters.Add("@CustomerId", SqlDbType.Int);
    custId.Direction = ParameterDirection.Input;
    custId.Value = 10;

    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}
private static string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["Lab3ConnectionString"].ConnectionString;
}
like image 852
russian Avatar asked Feb 01 '13 19:02

russian


People also ask

How can I retrieve data from SQL database?

In SQL, to retrieve data stored in our tables, we use the SELECT statement. The result of this statement is always in the form of a table that we can view with our database client software or use with programming languages to build dynamic web pages or desktop applications.

Can we connect C to database?

You can then add a new C source file and replace it with this content. Using the ODBC APIs SQLAllocHandle, SQLSetConnectAttr, and SQLDriverConnect, you should be able to initialize and establish a connection to your database.

What is the syntax for retrieving data from tables?

The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value'; In the above SQL statement: The SELECT clause specifies one or more columns to be retrieved; to specify multiple columns, use a comma and a space between column names.


2 Answers

You need to call Read before you can access data, Your code should be

While (dr.Read())
{

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

//close DataReader
dr.Close();
like image 171
rs. Avatar answered Sep 20 '22 18:09

rs.


Before you read column values from DataReader you must invoke Read() method from data reader.

if (dr.Read())
{
    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

You can also try:

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);
like image 26
Sławomir Rosiek Avatar answered Sep 19 '22 18:09

Sławomir Rosiek