Solved

how to populate dropdownlist in datagridview in asp.net

Posted on 2009-07-01
6
842 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
6 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 24760870
0
 
LVL 2

Accepted Solution

by:
puneetdudeja earned 500 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
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.…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

756 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