Paolo Duhaylungsod Paolo Duhaylungsod - 6 months ago 17
SQL Question

display a specific column in sql to a textbox asp.net

What i want to do is to get a specific column in my database. Currently i have ID, Username, Lastname, Firstname, Email, CreditRequest and Contact. I want credit request column to be displayed in my asp textbox. Any tricks you can share?

i am thinking something like this:

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
scn.Open();
SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM CreditRequests WHERE Username=@Username", scn);

Answer

You need to complete your code with the appropriate call to the method that executes the command and get back the result. I suppose that only one record is returned by that query, so calling ExecuteScalar is very efficient.

using (SqlConnection scn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
    scn.Open();
    SqlCommand cmd = new SqlCommand("SELECT CreditRequest FROM CreditRequests WHERE Username=@Username", scn);

    // Add the parameter required by the query....
    cmd.Parameters.Add("@Username", SqlDbType.NVarChar).Value = variableWithYouUserNameValue;

    // Run the query and get the single row/column returned
    object value = cmd.ExecuteScalar();

    // If it is not null (possible if the where fails) then put on textbox
    if(value != null)
        txtBoxCredit.Text = value.ToString();
}

Of course I don't know the real name of your textbox, so I have choosen a fictional name, change it with the real name of your textbox. The same for the variable that contains the current username to search for.

Comments