Solved

how to populate dropdownlist in datagridview in asp.net

Posted on 2009-07-01
6
837 Views
Last Modified: 2012-06-22
hi
i m working on a web application.
i use grid view
in this grid view i add  a dropdownlist as a template column which should be populate from database.
when user select a value from dropdownlist and update records then it updated database but not showing updated value  in  dropdownlist.


Any suggestion??????
Thanks
Sidharth
using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;
 

namespace CLRMS

{

    public partial class ManageWebsites : System.Web.UI.Page

    {

        

        SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                BindData();

                //DropDownListBIND();

            }

        }

         private void BindData()

        {

            try

            {

               

                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM websites", con);

                DataTable dt = new DataTable();

                da.Fill(dt);

                GridView1.DataSource = dt;

                GridView1.DataBind();

            }

            catch (Exception ex)

            {

                //con.Close();        

                Response.Write(ex.Message);

            }

        }
 

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

        {

            try

            {

                GridView1.EditIndex = e.NewEditIndex;

                BindData();

            }

            catch (Exception ex)

            {

                //con.Close();

                Response.Write(ex.Message);

            }

        }
 

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

        {
 

            try

            {

                GridView1.EditIndex = -1;

                BindData();

            }

            catch (Exception ex)

            {

                //con.Close();

                Response.Write(ex.Message);

            }

        }
 

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

        {

            try

            {

                

                DropDownList ddlTemp = GridView1.Rows[0].Cells[4].FindControl("DropDownList1") as DropDownList;       

                string  NOOFPAGES= ddlTemp.SelectedValue.ToString();

      
 

                if (((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text == "Insert")

                {

                    

                    SqlCommand cmd = new SqlCommand();
 

                    cmd.CommandText = "INSERT INTO websites(webname,weburl,NOOFPAGES,LINKSPERPAGE,STATICURL,ADMINLINKSPERPAGE) VALUES(@webname,@weburl,@NOOFPAGES,@LINKSPERPAGE,@STATICURL,@ADMINLINKSPERPAGE)";

                    cmd.Parameters.Add("@webname", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[0].Cells[2].Controls[0]).Text;
 

                    cmd.Parameters.Add("@weburl", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[0].Cells[3].Controls[0]).Text;

                    cmd.Parameters.Add("@NOOFPAGES", SqlDbType.NVarChar).Value = NOOFPAGES;

                        
 

                    cmd.Parameters.Add("@LINKSPERPAGE", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[0].Cells[5].Controls[0]).Text;

                    cmd.Parameters.Add("@STATICURL", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[0].Cells[6].Controls[0]).Text;

                    cmd.Parameters.Add("@ADMINLINKSPERPAGE", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[0].Cells[7].Controls[0]).Text;

                     
 

                    cmd.Connection = con;

                    con.Open();

                    cmd.ExecuteNonQuery();

                    con.Close();

                }

                else

                {

                    

                    SqlCommand cmd = new SqlCommand();
 

                    cmd.CommandText = "UPDATE WEBSITES SET webname=@webname,weburl=@weburl,LINKSPERPAGE=@LINKSPERPAGE,NOOFPAGES=@NOOFPAGES,STATICURL=@STATICURL,ADMINLINKSPERPAGE=@ADMINLINKSPERPAGE WHERE webid=@webid";
 

                    cmd.Parameters.Add("@webid", SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);

                    cmd.Parameters.Add("@webname", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
 

                    cmd.Parameters.Add("@weburl", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;

                    cmd.Parameters.Add("@NOOFPAGES", SqlDbType.NVarChar).Value = NOOFPAGES;

                       
 

                    cmd.Parameters.Add("@LINKSPERPAGE", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;

                    cmd.Parameters.Add("@STATICURL", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text;

                    cmd.Parameters.Add("@ADMINLINKSPERPAGE", SqlDbType.NVarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text;

                   

                    cmd.Connection = con;

                    con.Open();

                    cmd.ExecuteNonQuery();

                    con.Close();

                }

                GridView1.EditIndex = -1;

                BindData();

            }

            catch (Exception ex)

            {

                con.Close();

                Response.Write(ex.Message);

            }

        }
 

        

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

        {

            try

            {       SqlCommand cmd = new SqlCommand();

                    cmd.CommandText = "DELETE FROM websites WHERE webid=@webid";

                    cmd.Parameters.Add("@webid", SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[1].Text);

                    cmd.Connection = con;

                    con.Open();

                    cmd.ExecuteNonQuery();

                    con.Close();

                    BindData();

                

            }

            catch (Exception ex)

            {

                con.Close();

                Response.Write(ex.Message);

            }
 

        }

     
 

        protected void AddNew_Click(object sender, EventArgs e)

        {

             try

             {
 

                 SqlDataAdapter da = new SqlDataAdapter("SELECT webid,webname,weburl,NOOFPAGES,LINKSPERPAGE,STATICURL,ADMINLINKSPERPAGE FROM websites", con);

                 DataTable dt = new DataTable();

                 da.Fill(dt);
 

                 DataRow dr = dt.NewRow();

                 dt.Rows.InsertAt(dr, 0);
 

                 GridView1.EditIndex = 0;

                 GridView1.DataSource = dt;

                 GridView1.DataBind();
 

                 ((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";

             }

             catch (Exception ex)

             {

                 con.Close();

                 Response.Write(ex.Message);

             }

        }
 

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

        {
 

        }
 

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

        {
 

        }
 

        protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)

        {
 

        }

        protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)

        {

            // Increment Page Index  

            GridView1.EditIndex = -1;

            GridView1.PageIndex = e.NewPageIndex;
 

            BindData();

        }
 
 

       

    }

}

    
 
 
 
 
 
 
 

//.aspx file
 
 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Managewebsite.aspx.cs" Inherits="CLRMS.ManageWebsites" MasterPageFile="~/Site1.Master"%>
 
 
 
 

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

    <table class="style1">

        <tr>

            <td>

                &nbsp;</td>

        </tr>

        <tr>

            <td>

    <asp:Button ID="AddNew" runat="server" Text="Add New" 

    onclick="AddNew_Click" />

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;</td>

        </tr>

        <tr>

            <td>

                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 

                    CellPadding="4" DataKeyNames="WEBID" ForeColor="#333333" GridLines="None" 

                    Height="16px" OnRowCancelingEdit="GridView1_RowCancelingEdit" 

                    onrowcreated="GridView1_RowCreated" OnRowDeleting="GridView1_RowDeleting" 

                    OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" 

                    onselectedindexchanged="GridView1_SelectedIndexChanged1" Width="622px" 

                    onrowdatabound="GridView1_RowDataBound">

                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                    <Columns>

                        <%--<asp:BoundField DataField="NOOFPAGES" HeaderText="NO OF PAGES" />--%>

                        <asp:CommandField HeaderText="Edit-Update" ShowEditButton="True" />

                        <asp:BoundField DataField="WEBID" HeaderText="WEB ID" ReadOnly="True" />

                        <asp:BoundField DataField="WEBNAME" HeaderText="WEB NAME" />

                        <asp:BoundField DataField="WEBURL" HeaderText="WEB URL" />

                        <asp:TemplateField HeaderText="NO OF PAGES">

                            <ItemTemplate>

                                <asp:DropDownList ID="DropDownList1" runat="server">

                                    <asp:ListItem>1</asp:ListItem>

                                    <asp:ListItem>2</asp:ListItem>

                                    <asp:ListItem>3</asp:ListItem>

                                    <asp:ListItem>4</asp:ListItem>

                                    <asp:ListItem>5</asp:ListItem>

                                    <asp:ListItem>6</asp:ListItem>

                                    <asp:ListItem>7</asp:ListItem>

                                    <asp:ListItem>8</asp:ListItem>

                                    <asp:ListItem>9</asp:ListItem>

                                    <asp:ListItem>10</asp:ListItem>

                                    <asp:ListItem>11</asp:ListItem>

                                    <asp:ListItem>12</asp:ListItem>

                                    <asp:ListItem>13</asp:ListItem>

                                    <asp:ListItem>14</asp:ListItem>

                                    <asp:ListItem>15</asp:ListItem>

                                    <asp:ListItem>16</asp:ListItem>

                                    <asp:ListItem>17</asp:ListItem>

                                    <asp:ListItem>18</asp:ListItem>

                                    <asp:ListItem>19</asp:ListItem>

                                    <asp:ListItem>20</asp:ListItem>

                                </asp:DropDownList>

                            </ItemTemplate>

                        </asp:TemplateField>

                        <asp:BoundField DataField="LINKSPERPAGE" HeaderText="LINKS PER PAGE" />      

                         <asp:BoundField DataField="STATICURL" HeaderText="STATIC URL" />       

                         <asp:BoundField DataField="ADMINLINKSPERPAGE" HeaderText="ADMIN LINKS PER PAGE" />             

                        <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

                    </Columns>

                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />

                    <EditRowStyle BackColor="#999999" />

                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />

                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />

                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />

                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />

                </asp:GridView>

            </td>

        </tr>

    </table>

   

</asp:Content>

Open in new window

0
Comment
Question by:psaini172000
  • 3
6 Comments
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
0
 
LVL 2

Accepted Solution

by:
puneetdudeja earned 500 total points
Comment Utility
You are not binding your dropdownlist to the value you are fetching from your datasource.
Set the SelectedValue of your dropdownlist as shown in the following code snippet I have modified for you:


void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            DropDownList ddlTemp = e.Row.Cells[4].FindControl("DropDownList1") as DropDownList;

            ddlTemp.Items.FindByText(((DataRowView)e.Row.DataItem)["NOOFPAGES"].ToString()).Selected = true;
 

        }

Open in new window

0
 

Author Comment

by:psaini172000
Comment Utility
Thanks puneetdudeja:
i wiil try for ur code
and if it will work, i will accept it as a solution

Thanks for ur response
0
 
LVL 2

Expert Comment

by:puneetdudeja
Comment Utility
I forgot to add a check in the code.
First time, the RowDataBound is called for the Header Row of GridView which will not contain your drop down list.
So also check for Row to be a DataRow and then only bind your Drop Down list.
Modified code is in the following Code Snippet:
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

        {

if(e.Row.RowType==DataControlRowType.DataRow)

		{

            DropDownList ddlTemp = e.Row.Cells[4].FindControl("DropDownList1") as DropDownList;

            ddlTemp.Items.FindByText(((DataRowView)e.Row.DataItem)["NOOFPAGES"].ToString()).Selected = true;

 

        }

}

Open in new window

0
 
LVL 2

Expert Comment

by:puneetdudeja
Comment Utility
psaini172000,

Please accept the solution if your problem is solved, or if you have any follow up questions or problem pleasea ask and then close the question.

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Combine two columns 3 37
Hovering effect 9 28
Asp.net mvc entity issue 6 18
Re-position sub-options beneath the TAB 7 36
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now