Search code examples
c#databasevisual-studiovisual-studio-2015mdf

How could I show a row from the database to a textbox in Visual Studio 2015


I just started with Visual Studio and I was wondering on how could I echo out the first row under the maincategory_name column of my maincategory table to the textbox1. I followed a guide on how to insert data through the database but what I wanted to know is how could I print out one so I'm kinda confused how will I be able to do it as for know, the output I get on my textbox is: System.Data.SqlClient.SqlCommand

namespace TrialForDatabase
{
public partial class Form1 : Form
{

    SqlConnection sc = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename='C:\\Users\\flex\\Documents\\Visual Studio 2015\\Projects\\Inventory\\Inventory\\inventory.mdf';Integrated Security=True;Connect Timeout=30");
    SqlCommand cmd;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        sc.Open();
        cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
        textBox1.Text = cmd.ToString();
        sc.Close();
    }
}
}

Solution

  • This function first creates your SQL command, the executes it using SqlCommand.ExecuteReader(), then checks if you got any results using SqlDataReader.Read(), then displays the first column of the first row of your result to the Textbox:

       private void button1_Click(object sender, EventArgs e)
       {
           sc.Open();
           cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
           using (var reader = cmd.ExecuteReader()){
               if ( reader.Read() )
               {
                  textBox1.Text = reader.GetString(0);
               }
           };
    
           sc.Close();
       }
    

    See here for some more info on the classes used:

    https://msdn.microsoft.com/de-de/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx