插入点击时如何在gridview中绑定数据

问题描述:

插入点击我想要绑定日期到网格视图

我的代码是



Insert.cs

Insert click i want bind date to grid view
my code is

Insert.cs

  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();
        }
    }
}



当我点击插入时我想在gridview中显示以下记录


when i click insert i want to show record below in gridview

在你的bindgrid()函数中,你也必须编写一个Select查询来从数据库表中获取数据,这里你的数据表中没有数据。



请查看这个以获得帮助:





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+数据表+到+ GridView [ ^ ]
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[^]


根据您提供的代码。还有一些我觉得不到位的东西。



1)BindGrid():你没有从数据库中读取更新的数据,因此你的网格没有得到更新数据,因为您总是将网格绑定到虚拟对象,其中没有任何行。

要解决此问题,请在BindGrid方法中添加一个select查询,以从Insert1表中获取最新数据,并将其结果集绑定到Grid。

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.
SELECT Name,InvestmentType FROM Insert1





2)Button1_Click():在下面给出语句cmd.ExecuteNonQuery()之后调用BindGrid(),以便在单击按钮后立即更新数据。



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();
}