DDL is not showing correct value on Gridview row

Hi,
To the following Gridview
    <asp:GridView ID="GridView1" runat="server"  Width = "550px"
    AutoGenerateColumns = "false" 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:TemplateField HeaderText="Ite">
        <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_Ite_code" runat="server" Text='<%# Eval("Ite_code") %>' Visible="false" />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox id="tb_Ite_cd" runat="server" Text='<%# Eval("Ite_code") %>' Visible="false" />
        </EditItemTemplate>
        <FooterTemplate>
            <asp:TextBox id="tb_Ite_cd2" runat="server" Text='<%# Eval("Ite_code") %>' Visible="false" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Ite Rate">
        <ItemTemplate>
            <asp:Label ID="Ite_rate" runat="server"
                Text='<%# Eval("Ite_rate")%>'>
            </asp:Label>
        </ItemTemplate>
        <EditItemTemplate>
            <asp:Label ID="Ite_rate" runat="server" 
                Text='<%# Eval("Ite_rate")%>' >
            </asp:Label>
        </EditItemTemplate>
        <FooterTemplate>
            <asp:Label ID="Ite_rate2" runat="server" 
                Text='<%# Eval("Ite_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>
    ...
        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 Iterate order by Ite_code";
                //string sql = "Select * from Iterate";
                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();
        }

Open in new window

how to ensure the DDL is revealing the correct value of 1st column? I did call BindData() within Page_load event, but DDL is not showing the correct value for Column 1. What to adjust?
LVL 12
HuaMin ChenProblem resolverAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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

Maheshwar RSoftware DeveloperCommented:
Hi,

where are you binding the ddl values? could you send the code where your binding the ddl
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks. Here are the events
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl2");
                    if (ddl == null)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "InfoB", "javascript:alert('Unable to bind Edit row in Grid.');", true);
                        //lb_msg.Text = "Unable to bind Edit row in Grid.";
                        return;
                    }
                    else
                        this.BindDropDown(ddl);
                    Label lb_rt = (Label)e.Row.FindControl("Ite_rate");

                    if (Session["status"] != "Edit")
                        ddl.Enabled = false;
                    else
                        ddl.Enabled = true;
                }
                else
                {
                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddl");
                    if (ddl == null)
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "InfoB", "javascript:alert('Unable to bind row in Grid.');", true);
                        //lb_msg.Text = "Unable to bind row in Grid." + Convert.ToString(e.Row.RowState);
                        return;
                    }
                    else
                        this.BindDropDown(ddl);
                    Label lb_rt = (Label)e.Row.FindControl("Ite_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)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "InfoB", "javascript:alert('Unable to bind footer row in Grid.');", true);
                    //lb_msg.Text = "Unable to bind footer row in Grid.";
                    return;
                }
                else
                    this.BindDropDown(ddl);
                Label lb_rt = (Label)e.Row.FindControl("Ite_rate");

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

        private void BindDropDown(DropDownList para_ddl)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;

            cmd.CommandText = "select [rec_id],[currency_code] as [currency_code] from [savingrate] order by 1";

            para_ddl.DataSource = GetData(cmd);
            para_ddl.DataTextField = "currency_code";
            para_ddl.DataValueField = "rec_id";
            para_ddl.DataBind();
            para_ddl.Items.Insert(0, new ListItem("Please select"));
        }

Open in new window

0
Maheshwar RSoftware DeveloperCommented:
why dont you try the following code for binding the value to ddl, write this code after the grid is binded.

foreach (GridViewRow gvr in GridView1.Rows)
            {
                DropDownList ddl = (DropDownList)gvr.Cells[0].FindControl("ddl");

                sql = "select [rec_id],[currency_code] as [currency_code] from [savingrate] order by 1";
                ddl.DataTextField = "currency_code";
                ddl.DataValueField = "rec_id";
              

         DataAdapter ad = default(DataAdapter);
            DataSet ds1 = new DataSet();
            ad = new DataAdapter(sql, conDatabase);
            ad.Fill(ds1);
            dlist.DataSource = ds1.Tables[0].DefaultView;
            dlist.DataBind();                              
            }

Open in new window

0
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

HuaMin ChenProblem resolverAuthor Commented:
When should I run your current codes?
0
Maheshwar RSoftware DeveloperCommented:
in BindData(), after the line GridView1.DataBind();

Also change the connections for the SQL, the code i gave is general, replace DataAdapter with SQLDataAdapter etc
0
HuaMin ChenProblem resolverAuthor Commented:
Thanks. What is "dlist" to your codes?
0
Maheshwar RSoftware DeveloperCommented:
sorry, replace that with ddl
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks. There are 3 different records to the relevant table. But now the Gridview is showing the same value by the DDL, for all 3 records within the Gridview like
13abut the table actually is having these
13bHow to correct it?
0
Maheshwar RSoftware DeveloperCommented:
are you saving the rec_id in the database in the table Iterate ?

if yes then add the following code in the for loop

ddl.SelectedValue=gvr.Cells[1].Text

Open in new window


replace Cells[1] with the column number of the value of rec_id
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, I have these
            string sql2;
            foreach (GridViewRow gvr in GridView1.Rows)
            {
                DropDownList ddl = (DropDownList)gvr.Cells[0].FindControl("ddl");

                sql2 = "select [rec_id],[currency_code] as [currency_code] from [savingrate] order by 1";
                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.SelectedValue = gvr.Cells[0].Text;
                ddl.DataBind();
            }

Open in new window

but then I get this

[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) +12242935
   System.Web.UI.WebControls.ListControl.PerformSelect() +51
   Start._Default.BindData() +1089
   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

Open in new window


when going to the deployed page.
0
Maheshwar RSoftware DeveloperCommented:
write the following code in the for loop

                ddl.DataBind();
ddl.SelectedValue = gvr.Cells[0].Text;

Open in new window

Also check the value thats coming in  gvr.Cells[0].Text ... is it the value of rec_id?
0
HuaMin ChenProblem resolverAuthor Commented:
I did it in the way you suggested. But the result is the same, as still the DDL is not showing the relevant value correctly, per given record within Gridview.
0
Maheshwar RSoftware DeveloperCommented:
can u post the table script of Iterate
0
HuaMin ChenProblem resolverAuthor Commented:
It is having 3 records inside like
13e
0
Maheshwar RSoftware DeveloperCommented:
ok good, replace ddl.SelectedValue = gvr.Cells[0].Text; with ddl.Selecteditem.Text = gvr.Cells[0].Text;
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks. I have these

                ...

                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();
                ddl.SelectedItem.Text = gvr.Cells[0].Text;
...

Open in new window


but the DDL is still not showing the selected value, to the relevant record.
0
Maheshwar RSoftware DeveloperCommented:
Add the following code in Gridview Design Page after the <Columns>

 
<asp:BoundField DataField="ID" HeaderText="ID" >

Open in new window


Replace ID with the column name of the first field of the database
0
HuaMin ChenProblem resolverAuthor Commented:
Many thanks.
As I really do not want to show Rec_id (that is row ID) to Gridview, but if I put this
<asp:BoundField DataField="currency_code" Visible="false" HeaderText="Currency code" />

I get this
14aIf I remove

Visible="false"

in above, I get this
14bHow to hide 1st column in above?
0
Maheshwar RSoftware DeveloperCommented:
Add this line in for loop
 ddl.DataBind();
GridView1.Columns[0].Visible = true;
 ddl.SelectedItem.Text = gvr.Cells[0].Text;
GridView1.Columns[0].Visible = false;

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
HuaMin ChenProblem resolverAuthor Commented:
Many many thanks.
Originally it is showing this
14d
but once I've clicked "Edit" in above, it then shows this
14e
what to adjust to make DDL show the column value correctly?
0
Maheshwar RSoftware DeveloperCommented:
bind the values of ddl2 and ddl3 also in the for loop like you have done to ddl, the values will come for edit
0
HuaMin ChenProblem resolverAuthor Commented:
Many many thanks.
I have these

        private void BindData()
        {
            DataTable table = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString))
            {
                string sql = "Select * from savingrate order by currency_code";
                //string sql = "Select * from savingrate";
                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 [savingrate] 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;

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

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

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

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

Open in new window


when I go to the deployed project, 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.BindData() +1089
   Start._Default.Page_Load(Object sender, EventArgs e) +138
   System.Web.UI.Control.LoadRecursive() +70
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3177

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

Open in new window

0
Maheshwar RSoftware DeveloperCommented:
remove the line, ddl3.SelectedItem.Text = gvr.Cells[0].Text; for ddl2 and ddl3
0
HuaMin ChenProblem resolverAuthor Commented:
Sorry, I still 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.BindData() +1217
   Start._Default.Page_Load(Object sender, EventArgs e) +138
   System.Web.UI.Control.LoadRecursive() +70
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3177

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

Open in new window

using these
        private void BindData()
        {
            DataTable table = new DataTable();
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString))
            {
                string sql = "Select * from savingrate order by currency_code";
                //string sql = "Select * from savingrate";
                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 [savingrate] 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;

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

                SqlDataAdapter ad2 = default(SqlDataAdapter);
                DataSet ds2 = new DataSet();
                ad2 = new SqlDataAdapter(sql2, new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString));
                ad2.Fill(ds2);
                ddl2.DataSource = ds2.Tables[0].DefaultView;
                ddl2.DataBind();

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

                SqlDataAdapter ad3 = default(SqlDataAdapter);
                DataSet ds3 = new DataSet();
                ad3 = new SqlDataAdapter(sql2, new SqlConnection(ConfigurationManager.ConnectionStrings["Mssqlconn2"].ConnectionString));
                ad3.Fill(ds3);
                ddl3.DataSource = ds3.Tables[0].DefaultView;
                ddl3.DataBind();
            }
        }

Open in new window

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