开发者

issue with populating dropdownlist in gridview edit mode in c#

开发者 https://www.devze.com 2023-04-12 18:55 出处:网络
I am having editable Gridview with column named Country which has so long listing. When I am showing data the value of Country is in Label but when I choose edit should show DropDownList with country

I am having editable Gridview with column named Country which has so long listing.

When I am showing data the value of Country is in Label but when I choose edit should show DropDownList with country listings. I am able to show listings. it should show the country selected as that was in label.

I have tried with this but dropdownlist is filled with System.Row.DataRowView also it is not set at SelectedValue given as cvalue

aspx page

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

 void gvho开发者_如何学运维teldetail_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();      
             }

What could be wrong?


This worked for me. When populating the GridView, you should populate each DropDownList in the RowDataBound event:

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

Hope this helps!


This way you can make it work but I know there's a much better way to achieve this.. Try this for now...

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

    }


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


It's too late for the answer, but hope it would help someone. You can place the SelectedValue property inside your dropdownlist tag like below:

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

精彩评论

暂无评论...
验证码 换一张
取 消