DDL is not showing correct value on Gridview row

Hi,
Originally the records are shown fine below
16abut once I've clicked "Edit" button, the DDL is not revealing the value of 1st column well, like
16b
Why?

Here are the codes
    <asp:GridView ID="GridView1" runat="server"  Width = "550px"
    AutoGenerateColumns = "false" DataKeyNames="Item_code" Font-Names = "Arial"
    Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
    HeaderStyle-BackColor = "green" AllowPaging ="true"
    ShowFooter = "true" OnPageIndexChanging="GridView1_PageIndexChanging" 
    OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" 
    OnRowUpdating="GridView1_RowUpdating" PageSize = "10" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
    <Columns>
    <asp:BoundField DataField="Item_code" HeaderText="Item code" />
    <asp:TemplateField HeaderText="Item">
        <ItemTemplate>
            <asp:DropDownList ID="ddl" OnSelectedIndexChanged="ddl_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:DropDownList ID="ddl2" OnSelectedIndexChanged="ddl2_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:DropDownList ID="ddl3" OnSelectedIndexChanged="ddl3_IndexChanged" AutoPostBack="true" runat="server">
            </asp:DropDownList>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField Visible="false">
        <ItemTemplate>
            <asp:TextBox id="tb_Item_code" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox id="tb_Item_cd" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
        </EditItemTemplate>
        <FooterTemplate>
            <asp:TextBox id="tb_Item_cd2" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Act Rate">
        <ItemTemplate>
            <asp:Label ID="Item_rate" runat="server"
                Text='<%# Eval("Item_rate")%>'>
            </asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:Label ID="Item_rate" runat="server" 
                Text='<%# Eval("Item_rate")%>' >
            </asp:Label>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:Label ID="Item_rate2" runat="server" 
                Text='<%# Eval("Item_rate")%>' >
            </asp:Label>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Delete?">
        <ItemTemplate>
            <span onclick="return confirm('Are you sure to delete the record?')">
                <asp:LinkButton CssClass="forbutton" ID="lnkdelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete"/>
            </span>
        </ItemTemplate>
        <FooterTemplate>
            <asp:Button CssClass="forbutton" ID="btnadd" runat="server" Text="Add" OnClick="AddNewRec" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:CommandField ShowEditButton="true" />
    </Columns>
    <AlternatingRowStyle BackColor="White"/>
    <EditRowStyle BackColor="#efefef" />
    <FooterStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="true" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
    </asp:GridView>
    ...

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            lb_msg.Text = "";
            GridView1.EditIndex = e.NewEditIndex;
            this.PopulateData();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string selVal;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = "";
                        this.BindDropDown(ddl, selVal);
                    }

                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        /*if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else*/
                            selVal = "";
                        this.BindDropDown(ddl, selVal);
                    }
                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl3");
                if (ddl == null)
                {
                    return;
                }
                else
                {
                    /*if (e.Row.RowIndex >= 0)
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                    else*/
                        selVal = "";
                    this.BindDropDown(ddl, selVal);
                }
                Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                if (Session["status"] != "Edit")
                    ddl.Enabled = false;
                else
                    ddl.Enabled = true;
            }
        }

        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[Item_code] as [Item_code] from [Actrate] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "Item_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();
            //par_ddl.Items.Insert(0, new ListItem("Please select"));
            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (par_selVal != "")
                par_ddl.SelectedValue = par_selVal;
        }
        ...

Open in new window

LVL 11
HuaMin ChenProblem resolverAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Pratima PharandeCommented:
try this

par_ddl.ClearSelection();
par_ddl.Items.FindByValue(par_selVal).Selected = true;

also make sure par_selVal has value

also refer
http://www.aspsnippets.com/Articles/Populate-DropDownList-with-Selected-Value-in-EditItemTemplate-of-GridView-in-ASPNet.aspx
0
Lokesh B RDeveloperCommented:
Hi,

The following are the 2 options for you.

Option 1 :

If you want to use DataKeyNames="Item_code" ->  then change the following code because the DropDownList TextField is Item_code.

par_ddl.SelectedItem.Text  = par_selVal;


Option 2 :

Please set the DataKeyNames in your GridView as below.

<asp:GridView ID="GridView1" runat="server"   AutoGenerateColumns = "false" DataKeyNames="rec_id"

Since the DropDownList DataValueField is rec_id
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, I get this
Server Error in '/Start_dev' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   Start._Default.BindDropDown(DropDownList par_ddl, String par_selVal) +419
   Start._Default.GridView1_RowDataBound(Object sender, GridViewRowEventArgs e) +419
   System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource) +313
   System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +4779
   System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +94
   System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) +18
   System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +221
   System.Web.UI.WebControls.DataBoundControl.PerformSelect() +312
   Start._Default.PopulateData() +959
   System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +861
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3803

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

Open in new window

after having applied your 2 lines below
        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[Item_code] as [Item_code] from [Actrate] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "Item_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();
            //par_ddl.Items.Insert(0, new ListItem("Please select"));
            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (par_selVal != "")
            {
                //par_ddl.SelectedValue = par_selVal;
                par_ddl.ClearSelection();
                par_ddl.Items.FindByValue(par_selVal).Selected = true;
            }
        }

Open in new window

0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

HuaMin ChenProblem resolverAuthor Commented:
Thanks Lokesh.

You are correct. But how about the other 2 rows, not yet selected to edit?
16a
0
Lokesh B RDeveloperCommented:
Hi,

Paste this code.

 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string selVal;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        this.BindDropDown(ddl, selVal);
                    }

                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        this.BindDropDown(ddl, selVal);
                    }
                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl3");
                if (ddl == null)
                {
                    return;
                }
                else
                {
                    selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                    this.BindDropDown(ddl, selVal);
                }
                Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                if (Session["status"] != "Edit")
                    ddl.Enabled = false;
                else
                    ddl.Enabled = true;
            }
        }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Please see this
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //ds = GetDataSet();
            string selVal;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = "";
                        this.BindDropDown(ddl, selVal);
                    }

                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        /*if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else*/
                            selVal = "";
                        this.BindDropDown(ddl, selVal);
                    }
                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl3");
                if (ddl == null)
                {
                    return;
                }
                else
                {
                    /*if (e.Row.RowIndex >= 0)
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                    else*/
                        selVal = "";
                    this.BindDropDown(ddl, selVal);
                }
                Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                if (Session["status"] != "Edit")
                    ddl.Enabled = false;
                else
                    ddl.Enabled = true;
            }
        }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Lokesh,
It is OK and please omit my last reply in above.
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks Lokesh.

How can I control that, the DDL of 1st column, would be only editable, upon that I've selected "Edit" to the row, in the following?

16c
0
HuaMin ChenProblem resolverAuthor Commented:
Please also disregard my last request in above.
0
Lokesh B RDeveloperCommented:
Hi,

I have done some changes here. paste this code and check your possibilities.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string selVal;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // If Row is in Edit State
                if (e.Row.RowState == DataControlRowState.Edit)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        this.BindDropDown(ddl, selVal);
                        ddl.Enabled = true;
                    }
                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        this.BindDropDown(ddl, selVal);
                    }
                    Label lb_rt = (Label)e.Row.FindControl("Item_rate");
                    ddl.Enabled = false;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl3");
                if (ddl == null)
                {
                    return;
                }
                else
                {
                    selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                    this.BindDropDown(ddl, selVal);
                }
                Label lb_rt = (Label)e.Row.FindControl("Item_rate");

                if (e.Row.RowState == DataControlRowState.Edit)
                {
                    ddl.Enabled = false;
                }
                else
                {
                    ddl.Enabled = true;
                }
            }
        }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks Lokesh.

Due to "nbsp" shown to empty value of DDL below
https://dl.dropboxusercontent.com/u/40211031/tt99.png

I put these 2 line

            foreach (ListItem ddlItem in par_ddl.Items)
                ddlItem.Text = HttpUtility.HtmlDecode(ddlItem.Text);

Open in new window

within the below event
        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[currency_code] as [currency_code] from [currency] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "currency_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();

            foreach (ListItem ddlItem in par_ddl.Items)
                ddlItem.Text = HttpUtility.HtmlDecode(ddlItem.Text);

            //par_ddl.Items.Insert(0, new ListItem("Please select"));
            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (par_selVal != "")
            {
                par_ddl.SelectedItem.Text = par_selVal;
                /*par_ddl.ClearSelection();
                par_ddl.Items.FindByValue(par_selVal).Selected = true;*/
            }
        }

Open in new window

while the problem still persists. How to remove "nbsp" to DDL?
0
Lokesh B RDeveloperCommented:
Hi,

there is no problem with the code.

can you share the ASPX code and View Source of the DropDownList?
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, how to get View Source of the DDL?
0
Lokesh B RDeveloperCommented:
Hi,

Run the web page and Right click on the browser and click view source.

Find the par_ddl there and paste the code here
0
HuaMin ChenProblem resolverAuthor Commented:
Thanks. Here are what get
            <select name="GridView1$ctl02$ddl" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;GridView1$ctl02$ddl\&#39;,\&#39;\&#39;)&#39;, 0)" id="GridView1_ddl_0" disabled="disabled" class="aspNetDisabled">
				<option selected="selected" value="1">&amp;nbsp;</option>
				<option value="2">USD</option>
				<option value="3">RMB</option>
				<option value="1002">THB</option>
				<option value="1003">CAD</option>
				<option value="1004">GBP</option>
				<option value="1005">EUR</option>
				<option value="1006">CHF</option>
				<option value="1007">AUD</option>
				<option value="1008">NZD</option>
				<option value="1009">JPY</option>

			</select>

Open in new window

0
Lokesh B RDeveloperCommented:
Hi,

Replace this code and check

private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[currency_code] as [currency_code] from [currency] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "currency_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();

            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (!string.IsNullOrEmpty(par_selVal))
            {
                par_ddl.SelectedValue = par_selVal;
            }
           else
            {
                  par_ddl.SelectedIndex = 0;
              }
        }
        }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks. Using these

        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[currency_code] as [currency_code] from [currency] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "currency_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();

            //par_ddl.Items.Insert(0, new ListItem("Please select"));
            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (!string.IsNullOrEmpty(par_selVal))
            {
                par_ddl.SelectedItem.Text = par_selVal;
                /*par_ddl.ClearSelection();
                par_ddl.Items.FindByValue(par_selVal).Selected = true;*/
            }
            else
                par_ddl.SelectedIndex = 0;
        }

Open in new window

       
I still get the same problem.
0
Lokesh B RDeveloperCommented:
Hi,

You need to change the following code.

if (!string.IsNullOrEmpty(par_selVal))
{
          par_ddl.SelectedValue = par_selVal;
}
0
HuaMin ChenProblem resolverAuthor Commented:
But then I've got this
Server Error in '/Start_dev' Application.

'ddl' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.ArgumentOutOfRangeException: 'ddl' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 


[ArgumentOutOfRangeException: 'ddl' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value]
   System.Web.UI.WebControls.ListControl.PerformDataBinding(IEnumerable dataSource) +12203615
   System.Web.UI.WebControls.ListControl.PerformSelect() +51
   Start._Default.BindData() +947
   Start._Default.Page_Load(Object sender, EventArgs e) +139
   System.Web.UI.Control.LoadRecursive() +71
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

Open in new window

due to the current change.
0
Lokesh B RDeveloperCommented:
Hi,

Are you passing the ValueField/TextField to DropDownList in par_selVal?

try this

 if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByText(par_selVal);
                if (li != null)
                    li.Selected = true;
                else
                    par_ddl.SelectedIndex = 0;
            }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks Lokesh.

Here are the codes
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = "";
                        this.BindDropDown(ddl, selVal);

Open in new window


that is passing value to par_selVal.
0
HuaMin ChenProblem resolverAuthor Commented:
Using your recent codes, I still get the same problem.
0
Lokesh B RDeveloperCommented:
Hi,

selVal = "";
This is making the selected Value as "&nbsp;"

if (e.Row.RowIndex >= 0)
{
     selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
}

this.BindDropDown(ddl, selVal);

Open in new window



Change this in BindDropDown()

if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByValue(par_selVal);
                if (li != null)
                    li.Selected = true;
                else
                    par_ddl.SelectedIndex = 0;
            }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Thanks. Can I put null to selVal, as I still need to put one value to it, to Else condition, right?

Using these
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = null;
                            ...
        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[currency_code] as [currency_code] from [currency] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "currency_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();

            //par_ddl.Items.Insert(0, new ListItem("Please select"));
            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByValue(par_selVal);
                if (li != null)
                    li.Selected = true;
                else
                    par_ddl.SelectedIndex = 0;
                /*par_ddl.ClearSelection();
                par_ddl.Items.FindByValue(par_selVal).Selected = true;*/
            }
            else
                par_ddl.SelectedIndex = 0;
        }

Open in new window

I still get the same problem.
0
Lokesh B RDeveloperCommented:
Hi,

Can you post the screenshot after the changes?
0
HuaMin ChenProblem resolverAuthor Commented:
Please see this
20
0
Lokesh B RDeveloperCommented:
HI,

1. Make the following changes in BindDropDown method.

   if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByValue(par_selVal);
                if (li != null)
                    li.Selected = true;
                else
                    par_ddl.SelectedIndex = 0;
            }
2. Run the application and share the view source.

3. Complete method here


       
private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select distinct [rec_id],[currency_code] as [currency_code] from [currency] order by 2";

            par_ddl.DataSource = GetData(cmd);
            par_ddl.DataTextField = "currency_code";
            par_ddl.DataValueField = "rec_id";
            par_ddl.DataBind();

            par_ddl.Items.Insert(0, new ListItem("Please select"));
            if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByValue(par_selVal);
                if (li != null)
                    li.Selected = true;
                else
                    par_ddl.SelectedIndex = 0;
            }
        }

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks. Here are the codes of DDL
            <select name="GridView1$ctl02$ddl" onchange="javascript:setTimeout(&#39;__doPostBack(\&#39;GridView1$ctl02$ddl\&#39;,\&#39;\&#39;)&#39;, 0)" id="GridView1_ddl_0" disabled="disabled" class="aspNetDisabled">
				<option selected="selected" value="1">&amp;nbsp;</option>
				<option value="2">USD</option>
				<option value="3">RMB</option>
				<option value="1002">THB</option>
				<option value="1003">CAD</option>
				<option value="1004">GBP</option>
				<option value="1005">EUR</option>
				<option value="1006">CHF</option>
				<option value="1007">AUD</option>
				<option value="1008">NZD</option>
				<option value="1009">JPY</option>

			</select>

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Taken from "View source".
0
Lokesh B RDeveloperCommented:
Hi,

I think you didn't change the code which i shared.

<option selected="selected" value="1">&amp;nbsp;</option>

what is the Text for value="1" ?
as value="2" is USD.
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, can this
        private void BindData()
        {
            DataTable table = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString))
            //using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=213461;Data Source=C:\inetpub\VS2012\DB1.accdb"))
            {
                string sql = "Select * from Actrate order by currency_code";
                //string sql = "Select * from Actrate";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                //using (OleDbCommand cmd = new OleDbCommand(sql, conn))
                {
                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    //using (OleDbDataAdapter ad = new OleDbDataAdapter(cmd))
                    {
                        ad.Fill(table);
                    }
                }
            }
            GridView1.DataSource = table;
            GridView1.DataBind();
            string sql2;
            foreach (GridViewRow gvr in GridView1.Rows)
            {
                sql2 = "select [rec_id],[currency_code] as [currency_code] from [currency] order by 1";

                DropDownList ddl = (DropDownList)gvr.Cells[0].FindControl("ddl");
                ddl.DataTextField = "currency_code";
                ddl.DataValueField = "rec_id";

                SqlDataAdapter ad = default(SqlDataAdapter);
                DataSet ds1 = new DataSet();
                ad = new SqlDataAdapter(sql2, new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString));
                ad.Fill(ds1);
                ddl.DataSource = ds1.Tables[0].DefaultView;
                ddl.DataBind();
                GridView1.Columns[0].Visible = true;
                ddl.SelectedItem.Text = gvr.Cells[0].Text;
                GridView1.Columns[0].Visible = false;
                ...

Open in new window


be the reason of the problem, as it is being called by "Page_load" event?
0
Lokesh B RDeveloperCommented:
Hi,

Change to this and try

 ddl.DataSource = ds1.Tables[0].DefaultView;
                ddl.DataBind();
                GridView1.Columns[0].Visible = true;

                if (!string.IsNullOrEmpty(gvr.Cells[0].Text))
                {
                    ListItem li = ddl.Items.FindByText(gvr.Cells[0].Text);
                    if (li != null)
                        li.Selected = true;
                    else
                        ddl.SelectedIndex = 0;
                }
                
                GridView1.Columns[0].Visible = false;

Open in new window

0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, I do the change but have got this
Stack Trace: 


[HttpException (0x80004005): Cannot have multiple items selected in a DropDownList.]
   System.Web.UI.WebControls.DropDownList.VerifyMultiSelect() +124
   System.Web.UI.WebControls.ListControl.RenderContents(HtmlTextWriter writer) +12202681
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +52
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +246
   System.Web.UI.WebControls.TableCell.RenderContents(HtmlTextWriter writer) +61
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +52
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +246
   System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +15
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +52
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer) +743
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +52
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +246
   System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +15
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel) +324
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   ASP.default_aspx.__Rendermain_form(HtmlTextWriter __w, Control parameterContainer) +386
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +131
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +394
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +49
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +246
   System.Web.UI.Page.Render(HtmlTextWriter writer) +40
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +150
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5363

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34249

Open in new window

0
Lokesh B RDeveloperCommented:
Hi,

I think all your code is messed up.

remove the for-each loop from BindData() and try
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, the foreach loop is to bind DDL of each row of Gridview, right?
0
HuaMin ChenProblem resolverAuthor Commented:
If we remove, it will not do what I describe, right?
0
HuaMin ChenProblem resolverAuthor Commented:
If we remove that, it will not do what I describe, right?
0
Lokesh B RDeveloperCommented:
Hi,

Just check whether it works or not.

Your BindData() should be inside IsPostBack

Page_Load()
{

if(!IsPostBack)
{
       BindData();
}


}
0
HuaMin ChenProblem resolverAuthor Commented:
Thanks. Yes, I have these
            if (!IsPostBack)
            {

                BindData();
                Session["status"] = "Edit";
            }

Open in new window

0
Lokesh B RDeveloperCommented:
Hi,

here is the complete sample as per your requirements.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateData();
            }
        }

        private void PopulateData()
        {
            DataTable table = new DataTable();
            DataColumn idColumn = table.Columns.Add("ID", typeof(System.Int32));
            table.Columns.Add("Item_Code", typeof(System.String));
            table.Columns.Add("Item_Rate", typeof(System.Decimal));
            table.PrimaryKey = new DataColumn[] { idColumn };

            table.Rows.Add(new object[] { 1, "HKD", 0.1000 });
            table.Rows.Add(new object[] { 2, "RMD", 0.4500 });
            table.Rows.Add(new object[] { 3, "USD", 0.4500 });
            table.Rows.Add(new object[] { 4, "HK", 0.125 });
            table.AcceptChanges();

            GridView1.DataSource = table;
            GridView1.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string selVal;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = null;

                        this.BindDropDown(ddl, selVal);
                    }

                    Label lb_rt = (Label)e.Row.FindControl("curr_rate");
                    ddl.Enabled = true;
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        return;
                    }
                    else
                    {
                        if (e.Row.RowIndex >= 0)
                            selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                        else
                            selVal = null;
                        this.BindDropDown(ddl, selVal);
                    }
                    Label lb_rt = (Label)e.Row.FindControl("curr_rate");

                    ddl.Enabled = false;
                }
            }

            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("ddl3");
                if (ddl == null)
                {
                    return;
                }
                else
                {
                    /*if (e.Row.RowIndex >= 0)
                        selVal = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
                    else*/
                    selVal = null;
                    this.BindDropDown(ddl, selVal);
                }
                Label lb_rt = (Label)e.Row.FindControl("curr_rate");

                ddl.Enabled = false;
            }
        }

        private void BindDropDown(DropDownList par_ddl, string par_selVal)
        {
            DataTable table = new DataTable();
            DataColumn idColumn = table.Columns.Add("ID", typeof(System.Int32));
            table.Columns.Add("Item_Code", typeof(System.String));

            table.PrimaryKey = new DataColumn[] { idColumn };

            table.Rows.Add(new object[] { 1, "HKD" });
            table.Rows.Add(new object[] { 2, "RMD" });
            table.Rows.Add(new object[] { 3, "USD" });
            table.Rows.Add(new object[] { 4, "HKB" });
            table.AcceptChanges();

            par_ddl.DataValueField = "ID";
            par_ddl.DataTextField = "Item_Code";
            par_ddl.DataSource = table;
            par_ddl.DataBind();

            par_ddl.Items.Insert(0, new ListItem("Please select"));

            if (!string.IsNullOrEmpty(par_selVal))
            {
                ListItem li = par_ddl.Items.FindByText(par_selVal);
                if (li != null)
                {
                    li.Selected = true;
                }
                else
                {
                    par_ddl.SelectedIndex = 0;
                }
            }
            else
            {
                par_ddl.SelectedIndex = 0;
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.PopulateData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }

Open in new window



<asp:GridView ID="GridView1" runat="server" Width="550px"
                AutoGenerateColumns="false" DataKeyNames="Item_code" Font-Names="Arial"
                Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
                HeaderStyle-BackColor="green" AllowPaging="true"
                ShowFooter="true" OnPageIndexChanging="GridView1_PageIndexChanging"
                OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing"
                OnRowUpdating="GridView1_RowUpdating" PageSize="10" OnRowDeleting="GridView1_RowDeleting" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:BoundField DataField="Item_code" HeaderText="Item code" />
                    <asp:TemplateField HeaderText="Item">
                        <ItemTemplate>
                            <asp:DropDownList ID="ddl" AutoPostBack="true" runat="server">
                            </asp:DropDownList>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddl2"  AutoPostBack="true" runat="server">
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:DropDownList ID="ddl3" AutoPostBack="true" runat="server">
                            </asp:DropDownList>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField Visible="false">
                        <ItemTemplate>
                            <asp:TextBox ID="tb_Item_code" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:TextBox ID="tb_Item_cd" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:TextBox ID="tb_Item_cd2" runat="server" Text='<%# Eval("Item_code") %>' Visible="false" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField ItemStyle-Width="150px" HeaderText="Act Rate">
                        <ItemTemplate>
                            <asp:Label ID="Item_rate" runat="server"
                                Text='<%# Eval("Item_rate")%>'>
                            </asp:Label>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <asp:Label ID="Item_rate" runat="server"
                                Text='<%# Eval("Item_rate")%>'>
                            </asp:Label>
                        </EditItemTemplate>
                        <FooterTemplate>
                            <asp:Label ID="Item_rate2" runat="server"
                                Text='<%# Eval("Item_rate")%>'>
                            </asp:Label>
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Delete?">
                        <ItemTemplate>
                            <span onclick="return confirm('Are you sure to delete the record?')">
                                <asp:LinkButton CssClass="forbutton" ID="lnkdelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
                            </span>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Button CssClass="forbutton" ID="btnadd" runat="server" Text="Add"  />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="true" />
                </Columns>
                <AlternatingRowStyle BackColor="White" />
                <EditRowStyle BackColor="#efefef" />
                <FooterStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="true" ForeColor="White" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#EFF3FB" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="true" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#F5F7FB" />
                <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                <SortedDescendingCellStyle BackColor="#E9EBEF" />
                <SortedDescendingHeaderStyle BackColor="#4870BE" />
            </asp:GridView>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.