我正在尝试向数据网格视图添加一个新行,然后将信息插入到我的数据库中。
我的代码下面的问题是它正在创建一个新的空行但是不允许我在其中添加任何内容。我希望能够在其中添加内容,然后点击我的按钮添加,将其添加到我的表中。
填充datagridview的方法
private void fillDataview()
{
OleDbCommand mycmdL = new OleDbCommand("SELECT UserID, FirstName, LastName, email, BoolAgent, BoolAdmin FROM Users WHERE (BoolAgent = true)", mycon);
OleDbDataAdapter myadapt = new OleDbDataAdapter(mycmdL);
myadapt.Fill(myset, "Users");
DataTable tbAgent = myset.Tables["Users"];
DataTable tbTemp = new DataTable();
DataRow myrow = null;
tbTemp = tbAgent.DefaultView.ToTable(true, "UserID", "FirstName", "LastName", "email");
tbTemp.Columns["FirstName"].ColumnName = "FirstName";
tbTemp.Columns["LastName"].ColumnName = "LastName";
tbTemp.Columns["email"].ColumnName = "email";
myrow = tbTemp.NewRow();
myrow["FirstName"] = string.Empty;
myrow["LastName"] = string.Empty;
myrow["email"] = string.Empty;
tbTemp.Rows.Add(myrow);
ViewState["CurrentTable"] = tbTemp;
GridView1.DataSource = tbTemp;
GridView1.DataBind();
}
我在我的按钮添加:
中调用此方法private void addNewAgent()
{
int row = 0;
if (ViewState["CurrentTable"] !=null)
{
DataTable mydt = (DataTable)ViewState["CurrentTable"];
DataRow myrow = null;
if (mydt.Rows.Count>0)
{
for (int i = 1; i <= mydt.Rows.Count; i++)
{
Label id = GridView1.Rows[row].Cells[0].FindControl("lbl_ID") as Label;
TextBox fn = GridView1.Rows[row].Cells[1].FindControl("txt_FirstName") as TextBox;
TextBox ln = GridView1.Rows[row].Cells[2].FindControl("txt_LastName") as TextBox;
TextBox email = GridView1.Rows[row].Cells[3].FindControl("txt_Email") as TextBox;
myrow = mydt.NewRow();
myrow["UserID"] = i + 1;
mydt.Rows[i - 1]["FirstName"] = fn;
mydt.Rows[i - 1]["LastName"] = fn;
mydt.Rows[i - 1]["email"] = email;
row++;
}
mydt.Rows.Add(myrow);
ViewState["CurrentTable"] = mydt;
GridView1.DataSource = mydt;
GridView1.DataBind();
}
else
{
Response.Write("view state is null");
}
}
SetPreviousData();
}
我的方法setpreviousdata:
private void SetPreviousData()
{
int row = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
// Label id = GridView1.Rows[row].Cells[0].FindControl("lbl_ID") as Label;
TextBox fn = GridView1.Rows[row].Cells[1].FindControl("txt_FirstName") as TextBox;
TextBox ln = GridView1.Rows[row].Cells[2].FindControl("txt_LastName") as TextBox;
TextBox email = GridView1.Rows[row].Cells[3].FindControl("txt_Email") as TextBox;
fn.Text = dt.Rows[i]["FirstName"].ToString();
ln.Text = dt.Rows[i]["LastName"].ToString();
email.Text = dt.Rows[i]["email"].ToString();
row++;
}
}
}
}
答案 0 :(得分:0)
我找到了解决方案。在datagridview中,模板字段需要作为文本框。
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:TextBox ID="txt_FirstName" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_FirstName" runat="server" Text='<%#Eval("FirstName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>