asp.net GridView没有正确更新

时间:2010-09-14 18:58:54

标签: c# asp.net aspxgridview

我有一个包含这些参数的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();
}

3 个答案:

答案 0 :(得分:1)

RowUpdatingRowUpdated在不同时间点火。看看这不是你的问题。

答案 1 :(得分:1)

您是否在回发时重新绑定了GridView?您应该只在初始加载时从数据库中获取数据:

if (!IsPostBack)
{
    Gridview1.Datasource = BLL.SomeClass.Load(SomeRecordId);
    GridView1.DataBind();
}

答案 2 :(得分:1)

尝试使用以下方法获取新值:

//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();