healxph0enix
healxph0enix

Reputation: 99

How do I connect gridview to sql using C# in asp.net?

I know how to connect, open, read, close as you see below. I also have awesome tutorial how to add update/delete etc.

I can connect dataTable to sql using asp.net controls, but I want to learn how to manipulate it from C#.

MasterCust is my gridview table name. How do I connect the to it?

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection Conn = new SqlConnection("Data Source=aserver;Initial Catalog=KennyCust;Persist Security Info=True;user id=sa;pwd=qwerty01");
        SqlDataReader rdr = null;
        string commandString = "SELECT * FROM MainDB";

        try
        {
            Conn.Open();
            SqlCommand Cmd = new SqlCommand(commandString, Conn);

            rdr = Cmd.ExecuteReader();

            while (rdr.Read())
            {
                Console.WriteLine(rdr[0]);
            }
        }
        finally
        {
            if (rdr != null)
            {
                rdr.Close();
            }
            if (Conn != null)
            {
                Conn.Close();
            }
        }
        //MasterCust.
        //MasterCust.DataSource = commandString;
        //MasterCust.DataBind();
    }

Edit: This code worked

            try
        {
            Conn.Open();
            SqlCommand Cmd = new SqlCommand(commandString, Conn);
            SqlDataAdapter sdp = new SqlDataAdapter(Cmd);
            DataSet ds = new DataSet();

            sdp.Fill(ds);
            //rdr = Cmd.ExecuteReader();
            MasterCust.DataSource = ds.Tables[0];
            MasterCust.DataBind();


            }

Upvotes: 1

Views: 9687

Answers (1)

Shyju
Shyju

Reputation: 218952

Set the GridView's Datasource property and simply call the DataBind method.

This code will work. ( Tested)

 SqlConnection Conn = new SqlConnection("Data Source=Localhost\\SQLEXPRESS;Initial Catalog=Flash2;Integrated Security=True;");
 SqlDataReader rdr = null;
 string commandString = "SELECT * FROM USER_MASTER";

 try
 {
        Conn.Open();
        SqlCommand Cmd = new SqlCommand(commandString, Conn);
        rdr = Cmd.ExecuteReader();

        MasterCustView.DataSource = rdr;
        MasterCustView.DataBind();
 }
 catch (Exception ex)
 {
      // Log error
 }
 finally
 {
     if (rdr != null)
     {
         rdr.Close();
     }
     if (Conn != null)
     {
         Conn.Close();
     }
  }

Upvotes: 1

Related Questions