【问题标题】:issue with populating dropdownlist in gridview edit mode in c#在 c# 的 gridview 编辑模式下填充下拉列表的问题
【发布时间】:2011-10-14 07:33:19
【问题描述】:

我有 editable Gridview 列名为 Country 的列表很长。

当我显示数据时,Country 的值在 Label 中,但是当我选择编辑时,应该显示带有国家/地区列表的 DropDownList。我能够显示列表。 it should show the country selected as that was in label.

我已经尝试过,但下拉列表中充满了System.Row.DataRowView,也没有设置为cvalue的SelectedValue

aspx 页面

<asp:TemplateField HeaderText="Country">
                            <ItemTemplate>
                                <asp:Label ID="lblCountry" runat="server" Text='<%#Bind("Country")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px"
                                    Width="194px">
                                    <asp:ListItem Value="-1">Select..</asp:ListItem>
                                    <asp:ListItem Value="af">Afghanistan</asp:ListItem>
                                    <asp:ListItem Value="ax">Aland Islands</asp:ListItem>
                                    <asp:ListItem Value="al">Albania</asp:ListItem>
                                 </asp:DropDownList>
                              <EditItemTemplate>  

.cs 文件

 void gvhoteldetail_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowState == DataControlRowState.Edit)
                {
                     string cnm="",cvalue="";
                     string getCountry = "Select * from tbl_countrynames where `Name`='" + cname + "'";
                     string getCountrynames = "Select * from tbl_countrynames";
                     MySqlConnection con = new MySqlConnection(connection);
                     MySqlCommand cmd1 = new MySqlCommand(getCountrynames, con);
                     DataSet ds1 = new DataSet();
                     MySqlDataAdapter da1 = new MySqlDataAdapter(cmd1);
                     da1.Fill(ds1);

                     MySqlCommand cmd = new MySqlCommand(getCountry, con);
                     DataSet ds = new DataSet();
                     MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                     da.Fill(ds);
                     if (ds.Tables[0].Rows.Count > 0)
                     {
                            cnm = ds.Tables[0].Rows[0]["Name"].ToString();
                            cvalue = ds.Tables[0].Rows[0]["Value"].ToString();
                       }
                   DropDownList ddlcountry = (DropDownList)e.Row.FindControl("ddlCCountry");
                   ddlcountry.DataSource = ds1;
                   ddlcountry.SelectedValue = cvalue;
                   ddlcountry.DataBind();      
             }

可能出了什么问题?

【问题讨论】:

    标签: c# asp.net c#-4.0 gridview drop-down-menu


    【解决方案1】:

    这对我有用。填充 GridView 时,应在 RowDataBound 事件中填充每个 DropDownList:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        numberFormatDA formatDA = new numberFormatDA();
    
        DataTable mytable = new DataTable();
        DataColumn formatIDcolumn = new DataColumn("fkNumberFormat");
        DataColumn formatNameColumn = new DataColumn("numberFormat");
    
        mytable.Columns.Add(formatIDcolumn);
        mytable.Columns.Add(formatNameColumn);
    
        DataSet ds = new DataSet();
        ds = formatDA.getNumberFormatsDS();
    
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            TextBox txtSite = (TextBox)e.Row.FindControl("txtIDSite");
    
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlNumberFormat");
            DataRow[] rows = ds.Tables[0].Select();
    
            foreach (DataRow row in rows)
            {
                DataRow newrow = mytable.NewRow();
                newrow["fkNumberFormat"] = row["idnumberFormat"];
                newrow["numberFormat"] = row["numberFormat"];
                mytable.Rows.Add(newrow);
            }
    
            ddl.DataSource = mytable;
            ddl.DataTextField = "numberFormat";
            ddl.DataValueField = "fkNumberFormat";
    
            int numberFormatID = 0;
            Label lblFormatID = (Label)e.Row.FindControl("numberFormatLabel");
            numberFormatID = Int32.Parse(lblFormatID.Text);
    
            ddl.SelectedValue = numberFormatID.ToString();
            ddl.DataBind();
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 我需要在编辑模式下从标签中获取值并设置该标签值的gridview的selectedItem
    • 这正是这段代码应该做的。您应该需要根据需要更改类。但这是要遵循的逻辑
    【解决方案2】:

    这样你可以让它工作,但我知道有一个更好的方法来实现这一点.. 现在试试这个...

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewRow gvr = GridView1.Rows[e.NewEditIndex];
            Label lb = (Label)gvr.FindControl("lblCountry");
    
            GridView1.EditIndex = e.NewEditIndex;
            binddata();
            getselected(lb.Text);
        }
    
    
        private void getselected(string text)
        {
            GridViewRow gvr = GridView1.Rows[GridView1.EditIndex];
    
            DropDownList dr = (DropDownList)gvr.FindControl("ddlCCountry");
            dr.SelectedIndex = dr.Items.IndexOf(dr.Items.FindByText(text));
    
        }
    

    【讨论】:

      【解决方案3】:
      protected void gvGeneralMaster_RowEditing(object sender, GridViewEditEventArgs e)
          {
              try
              {
                  if (clsGeneral._strRights[2] == "0")
                  {
                      //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);               
                      //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
                      Response.Redirect("UnauthorizedUser.aspx");
                  }
                  else
                  {
                      GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.NewEditIndex];
                      ViewState["COUNTRY"] = ((Label)gvRow.FindControl("lblCountry")).Text.Trim();
                      ViewState["STATE"] = ((Label)gvRow.FindControl("lblState")).Text.Trim();
      
                      gvGeneralMaster.EditIndex = e.NewEditIndex;
                      GetGeneralDetails();
                  }
              }
              catch (Exception ex)
              {
                  lblErrorMsg.Text = ex.Message.ToString();
                  if (!ex.Message.ToString().Contains("Thread was being aborted."))
                  {
                      //oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
                      ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
                      catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
                  }
              }
          }
      
          protected void gvGeneralMaster_RowUpdating(object sender, GridViewUpdateEventArgs e)
          {
              try
              {
                  if (clsGeneral._strRights[2] == "0")
                  {
                      //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);               
                      //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
                      Response.Redirect("UnauthorizedUser.aspx");
                  }
                  else
                  {
                      GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.RowIndex];
                      oPRP._GeneralCode = int.Parse(((Label)gvRow.FindControl("lblEGenCode")).Text.Trim());
                      oPRP._GenaralName = ((TextBox)gvRow.FindControl("txtECity")).Text.Trim();
                      oPRP._StateName = ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() : "";
                      oPRP._CountryName = ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() : "";
                      oPRP._Remarks = ((TextBox)gvRow.FindControl("txtERemarks")).Text.Trim();
                      oPRP._Active = ((CheckBox)gvRow.FindControl("chkEditActive")).Checked;
                      oPRP._ModifiedBy = Session["CurrentUser"].ToString();
                      oDAL.SaveUpdateGeneralMaster("UPDATE", oPRP);
      
                      gvGeneralMaster.EditIndex = -1;
                      GetGeneralDetails();
                  }
              }
              catch (Exception ex)
              {
                  lblErrorMsg.Text = ex.Message.ToString();
                  if (!ex.Message.ToString().Contains("Thread was being aborted."))
                  {
                      //oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
                      ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
                      catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
                  }
              }
          }
      

      【讨论】:

        【解决方案4】:

        答案为时已晚,但希望对某人有所帮助。您可以将SelectedValue 属性放在下拉列表标签中,如下所示:

         <asp:DropDownList SelectedValue='<% Eval("Country") %>' ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px" Width="194px">
           <asp:ListItem Value="-1">Select..</asp:ListItem>
           <asp:ListItem Value="af">Afghanistan</asp:ListItem>
           <asp:ListItem Value="ax">Aland Islands</asp:ListItem>
           <asp:ListItem Value="al">Albania</asp:ListItem>
         </asp:DropDownList>
        

        【讨论】:

          猜你喜欢
          • 2017-11-26
          • 2014-10-04
          • 2013-01-30
          • 2011-08-31
          • 1970-01-01
          • 2011-11-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多