0

我有一个具有以下属性的 GridView:

OnRowUpdating="GridViewRowUpdateEventHandler"

在 GridView 中,我有以下控件:

<asp:TemplateField HeaderText="Progress" SortExpression="progress">
    <ItemTemplate>
        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
            <asp:ListItem Value="0">Incomplete</asp:ListItem>
            <asp:ListItem Value="1">Complete</asp:ListItem>
        </asp:DropDownList>
    </ItemTemplate>
</asp:TemplateField> 

GridViewRowUpdateEventHandler看起来像这样:

protected void GridViewRowUpdateEventHandler(object sender, GridViewUpdateEventArgs e)
{
    SqlConnection connection;
    SqlCommand command;

    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

    DropDownList ddlPriority = (DropDownList)row.FindControl("DropDownList1");

    using (connection = new SqlConnection(ConfigurationManager.AppSettings["connString"]))
    {
        using (command = new SqlCommand(@"update table1 set priority = @priority where id = @id", connection))
        {
            command.Parameters.Add("@priority", SqlDbType.Int, 1).Value = ddlPriority.SelectedValue;
            command.Parameters.Add("@id", SqlDbType.Int, 1).Value = row.RowIndex;

            connection.Open();
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

    GridView1.DataBind();
}

我根本没有收到任何错误消息,并且数据库中的相关行没有被更新。有谁知道为什么?

会不会是我看错了单元格Cells[5]?或者可能是因为我在 page_load 中什么都没有?或者也许是别的什么?

4

4 回答 4

1

由于 DropDiownList 在 a 中TemplateField并且它NamingContainer是 GridViewRow,因此您应该使用它row.FindControl来获取参考:

DropDownList ddlPriority = (DropDownList)row.FindControl("DropDownList1");

代替

DropDownList ddlPriority = (DropDownList)row.Cells[5].FindControl("DropDownList1");

但这不是您问题的核心,因为row.Cells[5].FindControl它在第 6 个单元格中也可能有效。否则你会得到一个NullreferenceException.

我假设您还在回发上绑定了 GridView,您应该检查该IsPostBack属性:

protected void Page_Load()
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

除此之外:

command.Parameters.Add("@id", SqlDbType.Int, 1).Value = row;

不起作用,因为row是 GridViewRow。最后,您还应该DataBind使用 GridView,否则将不会反映更改。

于 2012-08-31T15:15:05.070 回答
1

DataBind在 GridViewRowUpdateEventHandler 的末尾添加

GridView.DataBind();

为了找到控制

var ddlPriority = (DropDownList)row.FindControl("DropDownList1");
于 2012-08-31T15:15:13.807 回答
1

我假设您忘记重新绑定您的gridView 数据

gridview1.DataSource = YOUR_DATASOURCE;
gridview1.DataBind();

此外,您应该通过以下方式访问您的 dropDownList

DropDownList ddlPriority = (DropDownList) row.FindControl("DropDownList1");

编辑

发现另一个错误

command.Parameters.Add("@id", SqlDbType.Int, 1).Value = row; // wrong! primaryKey value needed!

这不起作用,因为行的类型为 GridViewRow。您应该分配我假设的 primaryKey 值!

无论您决定先做什么,我都会添加一些Debug.WriteLine(..)语句来查看将哪些值发送到 SQL Server。

于 2012-08-31T15:15:29.920 回答
1

我认为问题在于您使用该行的 rowIndex 作为 ID。所以你最后的 sql 命令会是这样的

update table1 set priority = 'blah' where id = 0 //(where its the first row and so on)

所以这是一个非常好的查询,它将运行没有错误或异常,但没有 ID = 0。您将它绑定到错误的 ID。您需要将其绑定到的是表中的 ID。

您可以通过运行 SQL 探查器来仔细检查这一点,您应该能够找到正在发送到数据库的查询。

于 2012-09-01T00:02:22.617 回答