在c#中以gridview编辑模式填充下拉列表的问题

时间:2011-10-14 07:33:19

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

我的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();      
             }

可能出现什么问题?

4 个答案:

答案 0 :(得分:2)

这对我有用。在填充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();
    }
}

希望这有帮助!

答案 1 :(得分:1)

通过这种方式你可以使它工作,但我知道有更好的方法来实现这一点.. 现在试试这个......

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

    }

答案 2 :(得分:1)

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

答案 3 :(得分:0)

这个答案为时已晚,但希望能帮助别人。您可以将SelectedValue属性放在dropdownlist标记中,如下所示:

 <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>