Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Insert click i want bind date to grid view
my code is

Insert.cs
C#
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Bindgrid();
        }
    }

    private void Bindgrid()
    {
        DataTable dummy = new DataTable();
        dummy.Columns.Add("ID");
        dummy.Columns.Add("Name");
        dummy.Columns.Add("InvestmentType");
        dummy.Rows.Add();
        GridView1.DataSource = dummy;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Insert1(Name,InvestmentType) values(@Name,@InvestmentType)", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
        cmd.Parameters.AddWithValue("@InvestmentType", TextBox2.Text);
        cmd.Connection = con;
        Label1.Text = "Inserted successfully..........";
        Bindgrid();
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }
}

when i click insert i want to show record below in gridview
Posted
Updated 19-May-15 2:34am
v2
Comments
Schatak 19-May-15 8:35am    
What is the error?

In your bindgrid() function, you have to write a Select query too to get the data from database table, here in your datatable there is no data present.

check this out for your help:


http://www.aspsnippets.com/Articles/How-to-bind-GridView-with-DataReader-in-ASPNet-using-C-and-VBNet.aspx[^]

http://forums.asp.net/t/1093452.aspx?Bind+datatable+to+GridView[^]
 
Share this answer
 
According to the code you gave. There a couple of things which I feel are not in place.

1) BindGrid(): You are not reading updated data from database and hence your grid is not getting updated data as you are always binding your grid to dummy object which does not have any rows in it.
To fix this, add a select query in your BindGrid method to fetch the latest data from Insert1 table and bind its result set to Grid.
SQL
SELECT Name,InvestmentType FROM Insert1


2) Button1_Click(): Call BindGrid() after to the statement cmd.ExecuteNonQuery() as given below so that your updated data can come right away as soon as you click button.
Bindgrid();
try
{
  con.Open();
  cmd.ExecuteNonQuery();
  Bindgrid();
}
 
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