我是dotnet的新手,我正在尝试动态地为网格视图添加一行文本框。
在加载页面时,网格视图将以只读方式加载数据。
单击编辑按钮,第二行将加载文本框。我成功到了这里。现在,在这些文本框中输入一些数据时,我无法读取我的c#代码中的值。
这是我的代码段。任何人都可以帮助我。
ASP代码:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="justGrid._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<asp:TextBox ID="TextBox1" runat="server" Width="170px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="edit" />
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="save" />
<br />
</asp:Content>
C#代码:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
staticTable();
}
bindGrid();
}
protected void staticTable()
{
string[] NamesArray = new string[] { "RAM", "SAM", "TOM", "JERRY" };
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt = ds.Tables.Add();
dt.Columns.Add("Names", typeof(string));
for (int j = 1; j <= 5; j++)
{
dt.Columns.Add("" + j, typeof(string));
}
foreach (string l in NamesArray)
{
dt.Rows.Add(l);
}
dt.Rows[0][1] = "S";
dt.Rows[0][2] = "P";
dt.Rows[0][5] = "P";
dt.Rows[1][2] = "S";
dt.Rows[1][4] = "P";
dt.Rows[2][3] = "S";
dt.Rows[3][1] = "U";
dt.Rows[3][5] = "P";
ViewState["CurrentTable"] = dt;
GridView1.DataSource = ds;
// GridView1.DataBind();
}
protected void bindGrid()
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int k = 1; k <= 5; k++)
{
TextBox tb1 = new TextBox();
tb1.Attributes.Add("runat", "server");
tb1.Width = 15;
tb1.ID = "TBID" + k;
tb1.Text = GridView1.Rows[1].Cells[k].Text.Trim().Replace(" ", string.Empty);
GridView1.Rows[1].Cells[k].Controls.Add(tb1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox box1 = (TextBox)GridView1.Rows[1].Cells[1].FindControl("TBID1");
TextBox1.Text = box1.Text;
}
}
注意:仅用于测试目的..尝试在文本框中显示第2行第1列值。
答案 0 :(得分:0)
foreach (GridViewRow row in GridView1.Rows)
{
TextBox box1 = row.FindControl("TBID") as TextBox;
if (box1 != null)
{
string value = box1.Text;
}
}