Improve company productivity with a Business Account.Sign Up

x
?
Solved

how to populate dropdownlist in datagridview in asp.net

Posted on 2009-07-01
6
Medium Priority
?
858 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
5 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 24760870
0
 
LVL 2

Accepted Solution

by:
puneetdudeja earned 2000 total points
ID: 24760896
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
ID: 24846655
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
ID: 24846694
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
ID: 24982059
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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.

Join & Write a Comment

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
There is a wide range of advantages associated with the use of ASP.NET. This is why this programming framework is used to create excellent enterprise-class websites, technologies, and web applications.
Hi, this video explains a free download that you can incorporate into your Access databases, or use stand-alone for contact management. Contacts -- Names, Addresses, Phone Numbers, eMail Addresses, Websites, Lists, Projects, Notes, Attachments…
To export Lotus Notes to Outlook PST or Exchange and Domino Server files to Exchange Server or PST files with ease, go for Kernel for Lotus Notes to Outlook conversion tool. Through the video, you can watch the conversion process. A common user with…

606 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