[英]asp.net GridView isn't updating properly
我有一個帶有以下參數的Gridview:
<asp:GridView runat="server" ID="ItemGrid" CssClass="Grid"
AutoGenerateColumns="false"
AutoGenerateDeleteButton="true" OnRowDeleting="RowDeleting"
AutoGenerateEditButton="true" onRowEditing="RowEdit"
OnRowCancelingEdit="CancelRowEdit" onRowUpdating="RowUpdating"
DataKeyNames="Item_ID">
<Columns>
<asp:BoundField HeaderText="Item" DataField="Item"/>
<asp:BoundField HeaderText="Family" DataField="Family"/>
<asp:BoundField HeaderText="Structure" DataField="Structure"/>
<asp:BoundField HeaderText="Updated" ReadOnly="true" DataFormatString="{0:d}" DataField="Updated"/>
</Columns>
</asp:GridView>
在更新時調用:
protected void RowUpdating(object sender, GridViewUpdateEventArgs e){
int Item_ID = (int)this.ItemGrid.DataKeys[e.RowIndex][0];
//Problem is something right here:
string Item = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string Family = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string Structure = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
ItemTableAdapter taItem = new ItemTableAdapter();
taItem.UpdateItem(Item, Family, Structure, DateTime.Now, Item_ID);
//just a <asp:Label> for seeing some output.
Alert.Text= string.Format("Item:{0}Family:{1}Structure:{2}",Item,Family,Structure);
this.ItemGrid.EditIndex = -1;
dataBind();
}
它會生成“更新/編輯/刪除”按鈕,我的“刪除”功能正好按照我想要的方式工作,“編輯”按鈕會按需生成可編輯的文本框。
我的問題是在更新部分中,字符串Item,Family,Structure正在獲取舊值,而不是我在生成的文本框中放入的新值。
如果我對值進行硬編碼,它們將更新到數據庫,並且DateTime.Now
始終在數據庫中正確更新,因此更新查詢可以正常工作。
我已經在這個/閱讀論壇上測試了幾天了。 我確定我只是錯過了一些我忽略了的簡單事物。
謝謝你的幫助。
編輯:已經回答了,但是對於那些好奇的人,這是我的dataBind();
protected void dataBind()
{
ItemTableAdapter taItem = new ItemTableAdapter();
this.ItemGrid.DataSource = taItem.GetActive();
this.ItemGrid.DataBind();
}
RowUpdating
和RowUpdated
在不同的時間觸發。 看看那不是你的問題。
您是否錯誤地在回發時重新綁定了GridView? 您只應在初始加載時從數據庫中獲取數據:
if (!IsPostBack)
{
Gridview1.Datasource = BLL.SomeClass.Load(SomeRecordId);
GridView1.DataBind();
}
嘗試使用以下方法獲取新值:
//string Item = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
//string Family = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
//string Structure = ((TextBox)ItemGrid.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
string Item = e.NewValues["Item"].ToString();
string Family = e.NewValues["Family"].ToString();
string Structure = e.NewValues["Structure"].ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.