从gridview更新事件更新数据表
本文关键字:更新 数据表 事件 gridview | 更新日期: 2023-09-27 18:17:19
我有一个数据表,我用数据填充,但是如果我想编辑行,我得到一个错误
无法强制转换类型为"System.Web.UI.WebControls"的对象。DataControlLinkButton' to type 'System.Web.UI.WebControls.TextBox'.
填充gridview的代码是public void addTochkout(string type, string no)
{
DataTable dt = (DataTable)Session["table_chkout"];
DataRow dr = dt.NewRow();
dr[0] = type;
dr[1] = no;
dt.Rows.Add(dr);
Session["table_detail"] = dt; //save dt to new session
gridbind();
}
public void gridbind()
{
//gridview
if (Session["table_detail"] != null)
{
DataTable dt = (DataTable)Session["table_detail"];
if (dt.Rows.Count > 0)
{
chkoutDetail.DataSource = dt;
chkoutDetail.DataBind();
string countitems = dt.Rows.Count.ToString();
Session["cart_counter"] = countitems;
}
}
else
{
chkoutDetail.DataSource = null;
chkoutDetail.DataBind();
}
}
现在,当我尝试更新gridview时,我从
行得到上面的错误dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
出错的整个代码块是
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
//Update the values.
GridViewRow row = chkoutDetail.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Price"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
//Reset the edit index.
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
}
如果你能帮我解决这个问题,我将非常感激。西蒙
注意,当您启用Edit选项时,网格视图中行编辑模式的第一个和第二个单元格是链接按钮(更新和取消)。所以在获取
行的文本框时可能需要改变索引//Cell number 2 for the first textbox. 0 for update link and 1 for cancel link
dt.Rows[row.DataItemIndex]["TicketType"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
我刚发完帖子就发现了我的问题,但是它不允许我回答这个问题。
这是我的解决方案
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
// //Update the values.
string type = e.NewValues[0].ToString();
string qty = e.NewValues[1].ToString();
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table_detail"];
dt.Rows[e.RowIndex]["TicketType"] = type;
dt.Rows[e.RowIndex]["TicketNo"] = qty;
dt.AcceptChanges();
chkoutDetail.EditIndex = -1;
//Bind data to the GridView control.
gridbind();
int value1 = Convert.ToInt32(ddtickettype.SelectedItem.Value);
int value2 = Convert.ToInt32(ddTicketno.SelectedItem.Value);
string tType = ddtickettype.SelectedItem.Text;
string tNo = ddTicketno.SelectedItem.Text;
int prevTotal = Convert.ToInt32(lblAmount.Text);
int total = (value1 * value2) + prevTotal;
Session["TotalAmount"] = total.ToString();
if (Session["TotalAmount"] != null)
{
lblAmount.Text = Session["TotalAmount"].ToString();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}