Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when web page is running grid view is displaying data from database on bind after we click on edit button the dropdown should be editable and on select is should display a list of cities .this is what i want can any one help me on this..


XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowcancelingEdit" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="userid" OnRowEditing="GridView1_RowEditing" >
           <Columns>
               <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="true" />
               <asp:TemplateField HeaderText="name">
               <ItemTemplate>
           <%# Eval("name")%>
         </ItemTemplate>
         <EditItemTemplate>
           <asp:TextBox runat="server" ID="txtname" Text='<%# Bind("name")%>' />
         </EditItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="age">
               <ItemTemplate>
             <%# Eval("age")%>
         </ItemTemplate>
         <EditItemTemplate>
             <asp:TextBox runat="server" ID="txtage" Text='<%# Bind("age")%>' />
         </EditItemTemplate>
               </asp:TemplateField>
               <asp:TemplateField HeaderText="City" SortExpression="City">
                   <EditItemTemplate>
                       <asp:DropDownList ID="DropDownList1" runat="server"
                           DataSourceID="SqlDataSource2" DataTextField="City" DataValueField="City"
                           SelectedValue='<%# Bind("city") %>' >
                       </asp:DropDownList>
                   </EditItemTemplate>
                   <ItemTemplate>
                       <asp:Label ID="Label1" runat="server" Text='<%# Bind("city") %>'></asp:Label>
                   </ItemTemplate>
               </asp:TemplateField>
               <asp:CommandField ShowEditButton="True" ButtonType="Button" />
           </Columns>
       </asp:GridView>

       <br />

   </div>
   <asp:SqlDataSource ID="SqlDataSource2" runat="server"
       ConnectionString="Server=ALOK\SQLEXPRESS; Database=Employee; uid=sa; pwd=1234;"
       SelectCommand="SELECT DISTINCT [City] FROM [employ]"></asp:SqlDataSource>
   <br />
   <br />
   </form>
Posted
Updated 7-Jan-14 5:43am
v4
Comments
ZurdoDev 6-Jan-14 10:14am    
Where are you stuck?
Alok.singh1166 6-Jan-14 10:35am    
I am not able to populate list of cities in dropdown it is showing only one city name which is coming from database
ZurdoDev 6-Jan-14 10:37am    
SELECT DISTINCT [City] FROM [employ] -- that is your Sql, right? Do you only have 1 distinct city in employ?
Alok.singh1166 6-Jan-14 10:59am    
yes in database i have only one city but i want to add many cities how to achive that
ZurdoDev 6-Jan-14 11:00am    
Achieve what? More cities in the database? Add more. Allow users to add them? Create a UI for that. What are you actually stuck on?

Quote:
yes in database i have only one city but i want to add many cities how to achive that
From your comment, it is quite clear that the you have only one city in Database table.

If you want to show more cities, then just add more cities in that table either manually in Database Management Software or build some aspx page to insert cities to that table.

After that, it will automatically reflect on GridView DropDownList.
 
Share this answer
 
In source view
ASP.NET
<asp:dropdownlist id="DropDownList1" runat="server" xmlns:asp="#unknown"></asp:dropdownlist>
In code behind
In row editing event
C#
DropdownList ddl=(DropdownList)GridView1.Rows[e.RowIndex].FindControl("DropdownList");
//take city name in dataset ds and bind that data to GridView
//to make selection in dropdownlist
ddl.SelectedItem=ddl.Items.FindByText("city");
 
Share this answer
 
Comments
Alok.singh1166 6-Jan-14 14:07pm    
Cannot implicitly convert type 'System.Web.UI.WebControls.ListItem' to 'string'
-------------------------
Things are working fine under ddl.Items.FindByText("city"); this error is coming please do the nees full
This was my markup
--------------
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>


        <br />

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCancelingEdit="GridView1_RowcancelingEdit" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="userid" OnRowEditing="GridView1_RowEditing" >
            <Columns>
                <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="true" />
                <asp:TemplateField HeaderText="name">
                <ItemTemplate>
            <%# Eval("name")%>
          </ItemTemplate>
          <EditItemTemplate>
            <asp:TextBox runat="server" ID="txtname" Text='<%# Bind("name")%>' />
          </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="age">
                <ItemTemplate>
              <%# Eval("age")%>
          </ItemTemplate>
          <EditItemTemplate>
              <asp:TextBox runat="server" ID="txtage" Text='<%# Bind("age")%>' />
          </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="city" SortExpression="city">
                    <EditItemTemplate>
                        <asp:DropDownList ID="DropDownList1"  runat="server" AutoPostBack="true"
                             DataTextField="city" DataValueField="city">
                            <asp:ListItem>Select</asp:ListItem>
                            <asp:ListItem>Kanpur</asp:ListItem>
                            <asp:ListItem>Lucknow</asp:ListItem>
                            <asp:ListItem>Mumbai</asp:ListItem>
                        </asp:DropDownList>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("city") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" ButtonType="Button" />
            </Columns>
        </asp:GridView>

        <br />

    </div>
     <br />
    <br />
    </form>
</body>
</html>





-------------------------------------------

This was my code

-------------------
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{

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

    }

    private void BindData()
    {
        string constr = @"Server=ALOK\SQLEXPRESS; Database=Employee; uid=sa; pwd=1234;";
        string query = "SELECT userid, name, age,city FROM employ";
        SqlDataAdapter da = new SqlDataAdapter(query, constr);
        DataTable table = new DataTable();
        da.Fill(table);
        GridView1.DataSource = table;
        GridView1.DataBind();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
                 
        BindData();
    }

    protected void GridView1_RowcancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        e.Cancel = true;
        GridView1.EditIndex = -1;
        BindData();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        var name = e.NewValues["name"] as string;
        var age = (string)e.NewValues["age"];
     
        DropDownList ddl = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropdownList1");
       
        string city = ddl.SelectedItem.Value;
        string userid = (string)e.Keys[0];
                       
       UpdateProduct(userid, name, age,city);

    }
    private void UpdateProduct(string userid, string name, string age, string city)
    {
        try
        {
            string constr = @"Server=ALOK\SQLEXPRESS; Database=Employee; uid=sa; pwd=1234;";
            string query = "UPDATE employ SET name = @name, age = @age , city=@city WHERE userid = @userid";


            SqlConnection con = new SqlConnection(constr);
            SqlCommand com = new SqlCommand(query, con);


            com.Parameters.Add("@name", SqlDbType.NVarChar).Value = name;
            com.Parameters.Add("@age", SqlDbType.Int).Value =Convert.ToInt32(age);
            com.Parameters.Add("@city", SqlDbType.NVarChar).Value = city;
            com.Parameters.Add("@userid", SqlDbType.NVarChar).Value = userid;


            con.Open();
            com.ExecuteNonQuery();
            con.Close();


            GridView1.EditIndex = -1;
            BindData();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }  

   
  
 }
 
Share this answer
 
v3
Comments
Is this an answer? Can you explain?
XML
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;

}
</style>
<script type="text/javascript">
function ConfirmationBox(username) {

var result = confirm('Are you sure you want to delete '+username+' Details?' );
if (result) {

return true;
}
else {
return false;
}
}
</script>
</head>
<body>
    <form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
        AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
        onrowcancelingedit="gvDetails_RowCancelingEdit"
        onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
        onrowupdating="gvDetails_RowUpdating"
        onrowcommand="gvDetails_RowCommand">

<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />

</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />

</FooterTemplate>
 </asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup= "validaiton"/>
</FooterTemplate>
</asp:TemplateField>
 <asp:TemplateField HeaderText="City">
 <EditItemTemplate>
 <asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="txtftrcity" runat="server"/>
 <asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="Designation">
 <EditItemTemplate>
 <asp:TextBox ID="txtstate" runat="server" Text='<%#Eval("Designation") %>'/>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="lblstate" runat="server" Text='<%#Eval("Designation") %>'/>
 </ItemTemplate>
 <FooterTemplate>
 <asp:TextBox ID="txtftrDesignation" runat="server"/>
  <asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
 </FooterTemplate>
 </asp:TemplateField>
 </Columns>
</asp:GridView>

    </div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
    </form>
</body>
</html>





---------------------------------------------------------------

codebehind
---------------
C#
<pre lang="c#"><pre lang="c#">

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
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;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
private SqlConnection con = new SqlConnection("Data Source=ALOK\\SQLEXPRESS;Initial Catalog=Employee; uid=sa; pwd=1234;");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}

}

protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}

protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtstate");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}

protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}

protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}

protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
//getting username from particular row
string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
//identifying the control in gridview
ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
//raising javascript confirmationbox whenver user clicks on link button
if (lnkbtnresult != null)
{
lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
}

}
}

protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}


}


}

}
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900