Click here to Skip to main content
15,921,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table that i have created in vs 2008 only. i write a code to insert values in database.And it executed succesfully. but how to write a code that dislay me all the entered values or without using seqel server 2008 r2 or so on.my code for inserting values is as follows:

C#
SqlConnection connection1 = new SqlConnection();
      SqlCommand Insert = new SqlCommand();
      Insert.Connection = connection1;
      connection1.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Acer\Documents\employeeDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
      int a = Convert.ToInt32(txtEmpId.Text);
      string b = txtEmpName.Text;
      int c = Convert.ToInt32(txtSalary.Text);
      string d = txtCity.Text;
      Insert.CommandText = "INSERT INTO Employeetable(EmpId,EmpName,Salary,City) Values (@a,@b,@c,@d)";
      Insert.Parameters.AddWithValue("@a", a);
      Insert.Parameters.AddWithValue("@b", b);
      Insert.Parameters.AddWithValue("@c", c);
      Insert.Parameters.AddWithValue("@d", d);
        Insert.Connection.Open();
      Insert.ExecuteNonQuery();
      Insert.Connection.Close();
      Response.Write("you have succesfully inserted data");
  }.

Thanks.tell me what code to write on read button that i have created on VS.
Posted
Updated 2-Jun-13 19:55pm
v3

1 solution

It's very similar, but you need to change the query, and use a different function. There are two basic ways: one uses a DataReader, the other a DataAdapter:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("SELECT iD, description FROM myTable WHERE Id = @ID", con))
        {
        com..Parameters.AddWithValue("@ID", myTextBox.Text);
        using (SqlDataReader reader = com.ExecuteReader())
            {
            while (reader.Read())
                {
                int id = (int) reader["iD"];
                string desc = (string) reader["description"];
                Console.WriteLine("ID: {0}\n    {1}", iD, desc);
                }
            }
        }
    }

C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT iD, description FROM myTable WHERE Id = @ID", con))
        {
        da.SelectCommand.Parameters.AddWithValue("@ID", myTextBox.Text);
        DataTable dt = new DataTable();
        da.Fill(dt);
        myDataGridView.DataSource = dt;
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900