Asp.net GridView RowUpdating返回旧值

时间:2012-10-27 09:35:21

标签: c# asp.net gridview


我正在尝试制作可编辑的GridView,当调用RowUpdating时,我从TextBoxes获得的值是旧值而不是新值。

我的GridView:

<asp:GridView ID="GVProducts" runat="server" AutoGenerateColumns="False" 
    CellPadding="4" BackColor="White" BorderColor="#3366CC" BorderStyle="None" 
    BorderWidth="1px" DataKeyNames="phoneId" 
    onrowcancelingedit="GVProducts_RowCancelingEdit" 
    onrowdeleting="GVProducts_RowDeleting" 
    onrowediting="GVProducts_RowEditing" onrowupdating="GVProducts_RowUpdating" 
    >
    <Columns>
        <asp:CommandField ButtonType="Button" EditText="ערוך" HeaderText="עריכה" 
            InsertText="הוסף" NewText="חדש" SelectText="בחר" ShowEditButton="True" 
            UpdateText="עדכן" CancelText="בטל" DeleteText="מחק" 
            InsertVisible="False" CausesValidation="False" />
        <asp:CommandField ButtonType="Button" CancelText="בטל" DeleteText="מחק" 
            EditText="ערוך" InsertText="הוסף" NewText="חדש" SelectText="בחר" 
            ShowDeleteButton="True" UpdateText="עדכן" HeaderText="מחיקה" 
            CausesValidation="False" />
        <asp:BoundField DataField="phoneId" HeaderText="מספר מכשיר" ReadOnly="True" 
            SortExpression="phoneId" />
        <asp:TemplateField HeaderText="צבע">
            <ControlStyle Width="100px" />
            <FooterStyle Width="100px" />
            <HeaderStyle Width="100px" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="חברה">
            <ItemTemplate>
                <asp:Label ID="lblBrand" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="דגם">
            <ItemTemplate>
                <asp:Label ID="lblModel" runat="server"></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="כמות" SortExpression="amount">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("amount") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("amount") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="כמות מינימלית" SortExpression="minAmount">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("minAmount") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("minAmount") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="price" HeaderText="מחיר" SortExpression="price" />
        <asp:TemplateField HeaderText="תמונה">
            <ItemTemplate>
                <asp:Image ID="img" runat="server" 
                    ImageUrl='<%# DataBinder.Eval(Container.DataItem,"pic","images/{0}") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
    <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
    <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
    <RowStyle BackColor="White" ForeColor="#003399" />
    <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
    <SortedAscendingCellStyle BackColor="#EDF6F6" />
    <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
    <SortedDescendingCellStyle BackColor="#D6DFDF" />
    <SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>

我的RowEditing(UpdateGVLabel无关):

protected void GVProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
    GVProducts.EditIndex = e.NewEditIndex;
    GVProducts.DataSource = products;

    UpdateGVlabel();
    //products = connection.GetData("Select * From Products", "Products");
    if (products.Rows.Count > 0)
    {
        ((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[6].Controls[1]).Text = products.Rows[e.NewEditIndex][4].ToString();
        ((TextBox)GVProducts.Rows[e.NewEditIndex].Cells[7].Controls[1]).Text = products.Rows[e.NewEditIndex][5].ToString();
    }
}

我的RowUpdating(UpdateGVLabel无关):

protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    bool abort = false;
    int amount = 0, minAmount = 0;
    int id = int.Parse(GVProducts.Rows[e.RowIndex].Cells[2].Text);
    try
    {
        amount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[6].Controls[1]).Text);
        minAmount = int.Parse(((TextBox)GVProducts.Rows[e.RowIndex].Cells[7].Controls[1]).Text);
        if (amount < minAmount)
        {
            MessageBox.Show("אין אפשרות להגדיר כמות שקטנה מהכמות המינימלית!");
            abort = true;
        }
        if (minAmount <= 0)
        {
            MessageBox.Show("כמות מינימלית לא יכולה להיות אפס או פחות!\nאם ברצונך לציין שהחנות לא מוכרת את המכשיר הזה, יש ללחוץ על \"מחק\"");
            abort = true;
        }
        if (amount < 0)
        {
            MessageBox.Show("כמות לא יכולה להיות שלילית");
            abort = true;
        }
    }
    catch (FormatException)
    {
        MessageBox.Show("כמויות חייבות להיות מספרים!");
        abort = true;
    }
    if (!abort)
    {
        connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
        products = connection.GetData("Select * From Products", "Products");
        connection.ChangeDatabase(cmd); GVProducts.EditIndex = -1;
        GVProducts.DataSource = products;

        UpdateGVlabel();

        MessageBox.Show("המכשיר נערך בהצלחה!");
    }
}

谢谢!

3 个答案:

答案 0 :(得分:1)

试试这个

protected void GVProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//your code

 if (!abort)
    {
        connection = new Connect(Server.MapPath("App_Data/ado1.mdb"));
        OleDbCommand cmd = new OleDbCommand();
        cmd.CommandText = "Update Products Set amount=" + amount + ", minAmount=" + minAmount + " Where phoneId=" + id;
        cmd.ExecuteNonQuery();//OR "connection.ChangeDatabase(cmd);" if it updates your database
        products = connection.GetData("Select * From Products", "Products");
        GVProducts.EditIndex = -1;
        GVProducts.DataSource = products;
        GVProducts.DataBind();
        UpdateGVlabel();

        MessageBox.Show("המכשיר נערך בהצלחה!");
    }
}

问题是你在从connection.ChangeDatabase(cmd);这样的表中获取数据后调用products = connection.GetData("Select * From Products", "Products");来更新你的数据库因此你总是从你的数据库中得到旧的值,你的数据库中的值也得到了更新。

在提供数据源GVProducts.DataBind();以绑定网格后,还要添加此GVProducts.DataSource = products;

答案 1 :(得分:0)

在行更新中编写代码

 int i=convert.toint32(e.NewValues["Standard"])

答案 2 :(得分:0)

IsPostBack()就是答案。我们必须检查页面是否被回发。如果没有,那么我们将绑定网格。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

参考:https://taditdash.wordpress.com/2014/06/30/why-gridview-rowupdating-event-is-not-giving-the-updated-values/