即时通讯使用asp.net和C#

我需要从文本框值填充gridview,

我的代码是

 <div>

    <table class="style1">
        <tr>
            <td>
                Name
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Address
                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
Number
                <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add" />
            </td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server">
                </asp:GridView>
            </td>
        </tr>
    </table>

</div>


那么我的.aspx代码是

protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add("Name");
        dt.Columns.Add("Address");
        dt.Columns.Add("Number");
        //First fill all the date present in the grid
        for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
        {
            if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
            {
            dr = dt.NewRow();
            dr["Name"] = GridView1.Rows[intCnt].Cells[0];
            dr["Address"] = GridView1.Rows[intCnt].Cells[1];
            dr["Number"] = GridView1.Rows[intCnt].Cells[2];
            dt.Rows.Add(dr);
            }
        }
        dr = dt.NewRow();
        dr["Name"] = TextBox1.Text;
        dr["Address"] = TextBox2.Text;
        dr["Number"] = TextBox3.Text;
        dt.Rows.Add(dr);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }


但结果是,将单行与值相加...
下一行的值未正确添加...
问题是
文本框值的第二个条目的存储方式类似于“ System.Web.UI.WebControls.DataControlFieldCell”显示在第二行的每个单元格中...

最佳答案

它应该像

  dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;


这就是您无法正确获得价值的原因。

  for (int intCnt = 0; intCnt < GridView1.Rows.Count; intCnt ++)
        {
            if (GridView1.Rows[intCnt].RowType == DataControlRowType.DataRow)
            {
            dr = dt.NewRow();
            dr["Name"] = GridView1.Rows[intCnt].Cells[0].Text;
            dr["Address"] = GridView1.Rows[intCnt].Cells[1].Text;
            dr["Number"] = GridView1.Rows[intCnt].Cells[2].Text;
            dt.Rows.Add(dr);
            }
        }

10-05 18:45