单击按钮,将文本框中的数据添加到GridView

时间:2014-03-08 01:14:10

标签: c# asp.net gridview

我有1个Dropdownlist和3个Textboxes,我想从文本框中添加数据,点击按钮后会将它们添加到GridView

<asp:DropdownList ID="ddlClassification" runat="server" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>Sample 1</asp:ListItem>
<asp:ListItem>Sample 2</asp:ListItem>
<asp:ListItem>Sample 3</asp:ListItem>
</asp:DropdownList>

<asp:TextBox ID="tbCost" runat="server" Width="100" ></asp:TextBox>
<asp:TextBox ID="tbAccumulate" runat="server" Width="100" ></asp:TextBox>
<asp:TextBox ID="tbNRV" runat="server" Width="100" ></asp:TextBox>

<asp:Button ID="btnAdd" runat="server" Text="ADD" onclick="btnAdd_Click" />

这就是我在代码背后的内容

public partial class SetUP : System.Web.UI.Page
{
    DataRow dr;
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("Classification");
        dt.Columns.Add("Cost");
        dt.Columns.Add("Accumulate");
        dt.Columns.Add("NRV");
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        dr = dt.NewRow();
        dr["Classification"] = ddlClassification.Text;
        dr["Cost"] = tbCost.Text;
        dr["Accumulate"] = tbAccumulate.Text;
        dr["NRV"] = tbNRV.Text;
        dt.Rows.Add(dr);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

我已经完成了一次,但现在我在GridView1.DataBind();上收到错误有人可以帮我解决问题

1 个答案:

答案 0 :(得分:1)

当您添加列时,请执行此操作

 dt.Columns.Add(new DataColumn("Classification", typeof(string)));

应该帮助你