C# 更新时无法从dropdownlist中提取selectedvalue/项

C# 更新时无法从dropdownlist中提取selectedvalue/项,c#,asp.net,C#,Asp.net,所以我在gridview中有一个dropdownlist,我试图从中获取selectvalues来更新我的数据库。我的问题是:当按下更新按钮时,它会忽略为所选值选择的内容,并获取首次加载dropdownlist时第一个值设置的内容 所以我的问题是:在gridview的更新事件期间,如何从dropdownlist中获取所选值 下面是我的代码隐藏,以及gridview的标记 代码隐藏: /// <summary> /// Handles the Click event of th

所以我在gridview中有一个dropdownlist,我试图从中获取selectvalues来更新我的数据库。我的问题是:当按下更新按钮时,它会忽略为所选值选择的内容,并获取首次加载dropdownlist时第一个值设置的内容

所以我的问题是:在gridview的更新事件期间,如何从dropdownlist中获取所选值

下面是我的代码隐藏,以及gridview的标记

代码隐藏:

    /// <summary>
/// Handles the Click event of the update button under edit in the gridview control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e) 
{
    int machineid;
    string machineid1;
    string machineTypeid;
    string machineModelid;

    //retrieve and set the data
    GridViewHolder.EditIndex = e.RowIndex;
    BindData();

    GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
    TextBox mID = row.FindControl("MachineIDText") as TextBox;
    DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
    DropDownList mModel = row.FindControl("MachineModelDropDown") as DropDownList;

    machineid1 = mID.Text;
    machineid = Convert.ToInt32(machineid1);
    machineTypeid = mType.SelectedValue;
    machineModelid = mModel.SelectedValue;

    try
    {
        if (machineTypeid != "empty" || machineModelid != "empty")
        {
            if (machineTypeid != "empty")
            {
                inputsService.UpdateMachineTypes(machineid, machineTypeid);
            }
            if (machineModelid != "empty")
            {
                inputsService.UpdateMachineModels(machineid, machineModelid);
            }
            UpdateSucceed.Visible = true;
            logger.Debug("Updating - Database successfully updated!");
        }
        else
        {
            UpdateFail.Visible = true;
            logger.Debug("Updating - Database had no data selected to be updated.");
        }
    }
    catch (Exception ex)
    {
        logger.ErrorFormat("Updating - Failed to update the table, ex = {0}", ex);
    }
}

/// <summary>
/// Handles the Click event of the cancel button under edit in the gridview control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
protected void GridViewHolder_Canceling(object sender, GridViewCancelEditEventArgs e)
{
    //reset the edit index
    GridViewHolder.EditIndex = -1;
    //Bind data to GridViewHolder
    BindData();
}

protected void GridViewHolder_DataBound(object sender, GridViewRowEventArgs e)
{
    if (this.GridViewHolder.EditIndex != -1)
    {
        DropDownList mType = e.Row.FindControl("MachineTypeDropDown") as DropDownList;
        DropDownList mModel = e.Row.FindControl("MachineModelDropDown") as DropDownList;
    }
}

protected void GridViewHolder_Editing(object sender, GridViewEditEventArgs e)
{
    //set the edit index to a new value
    GridViewHolder.EditIndex = e.NewEditIndex;
    //Bind data to gridviewholder
    BindData();
}

#endregion

#region Private Methods

private void BindData()
{
    GridViewHolder.DataSource = Session["MachineTable"];
    GridViewHolder.DataBind();
}
//
///处理gridview控件中“编辑”下“更新”按钮的单击事件。
/// 
///事件的来源。
///包含事件数据的实例。
受保护的无效GridViewHolder_更新(对象发送方,GridViewUpdateEventArgs e)
{
int-machineid;
弦机1;
字符串machineTypeid;
字符串机器模型;
//检索并设置数据
GridViewHolder.EditIndex=e.RowIndex;
BindData();
GridViewRow行=(GridViewRow)GridViewHolder.Rows[e.RowIndex];
TextBox mID=row.FindControl(“MachineIDText”)作为TextBox;
DropDownList mType=row.FindControl(“MachineTypeDropDown”)作为DropDownList;
DropDownList mModel=row.FindControl(“MachineModelDropDown”)作为DropDownList;
machineid1=中间文本;
machineid=Convert.ToInt32(machineid1);
machineTypeid=mType.SelectedValue;
MachineModeId=mModel.SelectedValue;
尝试
{
if(machineTypeid!=“empty”| | machineModelid!=“empty”)
{
if(machineTypeid!=“空”)
{
inputsService.UpdateMachineTypes(machineid、machineTypeid);
}
if(machineModelid!=“空”)
{
inputsService.UpdateMachineModels(machineid、machineModelid);
}
UpdateSucceed.Visible=true;
Debug(“更新-数据库已成功更新!”);
}
其他的
{
UpdateFail.Visible=true;
Debug(“更新-数据库没有选择要更新的数据”);
}
}
捕获(例外情况除外)
{
ErrorFormat(“更新-更新表失败,ex={0}”,ex);
}
}
/// 
///处理gridview控件中“编辑”下“取消”按钮的单击事件。
/// 
///事件的来源。
///包含事件数据的实例。
受保护的无效GridViewHolder\u取消(对象发送方,GridViewCancelEditEventArgs e)
{
//重置编辑索引
GridViewHolder.EditIndex=-1;
//将数据绑定到GridViewHolder
BindData();
}
受保护的无效GridViewHolder_数据绑定(对象发送方,GridViewRowEventArgs e)
{
如果(this.GridViewHolder.EditIndex!=-1)
{
DropDownList mType=e.Row.FindControl(“MachineTypeDropDown”)作为DropDownList;
DropDownList mModel=e.Row.FindControl(“MachineModelDropDown”)作为DropDownList;
}
}
受保护的无效GridViewHolder_编辑(对象发送者,GridViewEditEventArgs e)
{
//将编辑索引设置为新值
GridViewHolder.EditIndex=e.NewEditIndex;
//将数据绑定到gridviewholder
BindData();
}
#端区
#区域私有方法
私有void BindData()
{
GridViewHolder.DataSource=会话[“MachineTable”];
GridViewHolder.DataBind();
}
gridview标记:

<asp:GridView ID="GridViewHolder" 
                      runat="server" 
                      AllowPaging="True" 
                      AutoGenerateColumns="False" 
                      BackColor="Transparent" 
                      BorderColor="#999999" 
                      BorderStyle="Ridge" 
                      BorderWidth="3px" 
                      CellPadding="4" 
                      CellSpacing="2" 
                      DataSourceID="MachineDataSet" 
                      ForeColor="Black" 
                      HeaderStyle-HorizontalAlign="Center" 
                      HorizontalAlign="Center"  
                      RowStyle-HorizontalAlign="Center" 
                      Width="796px"
                      OnRowUpdating="GridViewHolder_Updating"
                      OnRowCancelingEdit="GridViewHolder_Canceling"
                      OnRowEditing="GridViewHolder_Editing"
                      OnRowDataBound="GridViewHolder_DataBound"                          
                      EnableViewState="False">
            <RowStyle BackColor="Transparent" 
                      HorizontalAlign="Center" />
            <Columns>
                <asp:TemplateField HeaderText="ID" 
                                   SortExpression="ID" 
                                   Visible="False">
                    <ItemTemplate>
                        <asp:Label ID="MachineIDLabel" 
                                   runat="server" 
                                   Text='<%# Bind("ID") %>'
                                   Visible="false"></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="MachineIDText" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="SiteName" 
                                HeaderText="Site Name" 
                                SortExpression="SiteName"
                                ReadOnly="true" />
                <asp:BoundField DataField="Name" 
                                HeaderText="Machine Name" 
                                ReadOnly="true" 
                                SortExpression="Name" />
                <asp:TemplateField HeaderText="Machine Type" 
                                   SortExpression="MachineType">
                    <ItemTemplate>
                        <asp:Label ID="MachineTypeLabel" 
                                   runat="server" 
                                   Text='<%# Bind("MachineType") %>'>
                        </asp:Label>                            
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="MachineTypeDropDown" 
                                          runat="server" 
                                          AppendDataBoundItems="True"                                                
                                          Height="21px" 
                                          Width="217px" 
                                          DataSourceID="GetMachineType" 
                                          DataTextField="Name" 
                                          DataValueField="ID">
                            <asp:ListItem Enabled="true" 
                                          Text="Select a Machine Type." 
                                          Value="empty">
                            </asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Machine Model" SortExpression="MachineModel">
                    <ItemTemplate>
                        <asp:Label ID="MachineModelLabel" 
                                   runat="server" 
                                   Text='<%# Bind("MachineModel") %>'>
                        </asp:Label>                            
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="MachineModelDropDown" 
                                          runat="server" 
                                          AppendDataBoundItems="True"                                                
                                          Height="21px" Width="217px" 
                                          DataSourceID="GetMachineModel" 
                                          DataTextField="Name" 
                                          DataValueField="ID">
                            <asp:ListItem Enabled="true" 
                                          Text="Select a Machine Model." 
                                          Value="empty">
                            </asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ButtonType="Button" 
                                  ShowEditButton="True"
                                  CausesValidation="false" >
                    <ItemStyle HorizontalAlign="Center" 
                               Wrap="True" />
                </asp:CommandField>
            </Columns>
            <FooterStyle BackColor="Transparent" />
            <PagerStyle BackColor="Transparent" 
                        ForeColor="Black" 
                        HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="Transparent" 
                              Font-Bold="True" 
                              ForeColor="White" />
            <HeaderStyle BackColor="Black" 
                         Font-Bold="True" 
                         ForeColor="White" 
                         HorizontalAlign="Center" />
     </asp:GridView>

非常感谢您的帮助或建议

谢谢

具有类型为
GridViewUpdateEventArgs
的事件参数。它有键值、旧值和新值的字典。不需要在GridViewRow上使用FindControl来获取它们

但是,获取旧值的主要原因是,在此事件中再次对其进行数据绑定。然后用数据源中的值覆盖所有更改

更新:似乎
下拉列表
选定值
不属于
新值
字典的一部分。因此,您可以将其添加到
行更新
事件中

protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e) 
{
    GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
    DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
    e.NewValues.Add("MachineType", mType.SelectedValue):
}
具有类型为
GridViewUpdateEventArgs
的事件参数。它有键值、旧值和新值的字典。不需要在GridViewRow上使用FindControl来获取它们

但是,获取旧值的主要原因是,在此事件中再次对其进行数据绑定。然后用数据源中的值覆盖所有更改

更新:似乎
下拉列表
选定值
不属于
新值
字典的一部分。因此,您可以将其添加到
行更新
事件中

protected void GridViewHolder_Updating(object sender, GridViewUpdateEventArgs e) 
{
    GridViewRow row = (GridViewRow)GridViewHolder.Rows[e.RowIndex];
    DropDownList mType = row.FindControl("MachineTypeDropDown") as DropDownList;
    e.NewValues.Add("MachineType", mType.SelectedValue):
}

您在gridview中关闭了viewstate,如果打开它会有区别吗?@ipr101当我打开viewstate时,它会抛出一个错误,在编辑模式下尝试运行“取消”或“更新”按钮时无法加载viewstate您在gridview中关闭了viewstate,如果您