Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Ajax ModalPopUpExtender Example to edit the gridview row values in asp.net

Mar 15, 2011
Introduction:

Here I will explain how to show the modal popup using Ajax ModalPopupExtender to edit Rows in a GridView using asp.net.

Description:

In my previous post I explained clearly how to show the gridview images with lightbox effect. Same way we can display popup using Ajax futures. In ajax we have ModalPopup extender to display data in Popup here I am doing sample to show pop up whenever user clicks on Edit button in gridview at that time I will display that particular gridview row data into Modal popup for that First design table in your database like this

Column Name
Data Type
Allow Nulls
UserId
int(set identity property=true)
No
UserName
varchar(50)
Yes
FirstName
varchar(50)
Yes
LastName
varchar(50)
Yes
City
varchar(50)
Yes
Designation
varchar(50)
Yes
After that enter some data in table to bind that data to gridview.

Now add AjaxControlToolkit.dll to your bin folder and design your aspx page like this


<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.modalBackground
{
background-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:GridView runat="server" ID="gvdetails" DataKeyNames="UserId" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="imgbtn" ImageUrl="~/Edit.jpg" runat="server" Width="25" Height="25" onclick="imgbtn_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
</Columns>
</asp:GridView>
<asp:Label ID="lblresult" runat="server"/>
<asp:Button ID="btnShowPopup" runat="server" style="display:none" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup" PopupControlID="pnlpopup"
CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
<asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="269px" Width="400px" style="display:none">
<table width="100%" style="border:Solid 3px #D55500; width:100%; height:100%" cellpadding="0" cellspacing="0">
<tr style="background-color:#D55500">
<td colspan="2" style=" height:10%; color:White; font-weight:bold; font-size:larger" align="center">User Details</td>
</tr>
<tr>
<td align="right" style=" width:45%">
UserId:
</td>
<td>
<asp:Label ID="lblID" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
UserName:
</td>
<td>
<asp:Label ID="lblusername" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
City:
</td>
<td>
<asp:TextBox ID="txtCity" runat="server"/>
</td>
</tr>
<tr>
<td align="right">
Designation:
</td>
<td>
<asp:TextBox ID="txtDesg" runat="server"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpdate" CommandName="Update" runat="server" Text="Update" onclick="btnUpdate_Click"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>
</div>
</form>
</body>
</html>
Here if you observe above code for ModalPopupExtender I have declared different properties to ModalPopupEtender now I will explain each property clearly

TargetControlID - The ID of the element that activates the modal popup.
Here I gave one button name  btnShowPopup but that button mode is in visible=false because it’s not necessary here we are triggering popup by calling show() function in button click codebehind but if we didn’t given that targetcontrolid to ModalPopupExtender it will throw error for that reason I gave target controlid.

PopupControlID - The ID of the element to display as a modal popup.
CancelControlID - The ID of the element that cancels the modal popup.
BackgroundCssClass - The CSS class to apply to the background when the modal popup is displayed.
 
After completion our aspx page design write the following namespaces in codebehind

C# Code

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
After completion of writing namespaces and write the following code


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGridData();
}
}
protected void BindGridData()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gvdetails.DataSource = dt;
gvdetails.DataBind();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set FirstName=@FirstName,LastName=@LastName, City=@City,Designation=@Designation where UserId=@UserId", con);
cmd.Parameters.AddWithValue("@FirstName", txtfname.Text);
cmd.Parameters.AddWithValue("@LastName", txtlname.Text);
cmd.Parameters.AddWithValue("@City", txtCity.Text);
cmd.Parameters.AddWithValue("@Designation", txtDesg.Text);
cmd.Parameters.AddWithValue("@UserId", Convert.ToInt32(lblID.Text));
cmd.ExecuteNonQuery();
con.Close();
lblresult.Text = lblusername.Text + " Details Updated Successfully";
lblresult.ForeColor = Color.Green;
BindGridData();
}
protected void imgbtn_Click(object sender, ImageClickEventArgs e)
{
ImageButton btndetails = sender as ImageButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
lblID.Text = gvdetails.DataKeys[gvrow.RowIndex].Value.ToString();
lblusername.Text = gvrow.Cells[1].Text;
txtfname.Text = gvrow.Cells[2].Text;
txtlname.Text = gvrow.Cells[3].Text;
txtCity.Text = gvrow.Cells[4].Text;
txtDesg.Text = gvrow.Cells[5].Text;
this.ModalPopupExtender1.Show();
}
VB.NET Code

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Class VBCode
Inherits System.Web.UI.Page
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ToString())
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridData()
End If
End Sub
Protected Sub BindGridData()
con.Open()
Dim cmd As New SqlCommand("Select * from Employee_Details", con)
Dim da As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
da.Fill(dt)
gvdetails.DataSource = dt
gvdetails.DataBind()
End Sub
Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As EventArgs)
con.Open()
Dim cmd As New SqlCommand("update Employee_Details set FirstName=@FirstName,LastName=@LastName, City=@City,Designation=@Designation where UserId=@UserId", con)
cmd.Parameters.AddWithValue("@FirstName", txtfname.Text)
cmd.Parameters.AddWithValue("@LastName", txtlname.Text)
cmd.Parameters.AddWithValue("@City", txtCity.Text)
cmd.Parameters.AddWithValue("@Designation", txtDesg.Text)
cmd.Parameters.AddWithValue("@UserId", Convert.ToInt32(lblID.Text))
cmd.ExecuteNonQuery()
con.Close()
lblresult.Text = lblusername.Text + " Details Updated Successfully"
lblresult.ForeColor = Color.Green
BindGridData()
End Sub
Protected Sub imgbtn_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
Dim btndetails As ImageButton = TryCast(sender, ImageButton)
Dim gvrow As GridViewRow = DirectCast(btndetails.NamingContainer, GridViewRow)
lblID.Text = gvdetails.DataKeys(gvrow.RowIndex).Value.ToString()
lblusername.Text = gvrow.Cells(1).Text
txtfname.Text = gvrow.Cells(2).Text
txtlname.Text = gvrow.Cells(3).Text
txtCity.Text = gvrow.Cells(4).Text
txtDesg.Text = gvrow.Cells(5).Text
Me.ModalPopupExtender1.Show()
End Sub
End Class
After that set your database connection in web.config like this

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Demo


Download sample code attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

97 comments :

Anonymous said...

good work

Anonymous said...

i am loving it

Anonymous said...

Thanks its awesome

Anonymous said...

nice man more valuable!!

narwal said...

nice great work

narwal said...

i want creat logs for my application please help me for this please please

TheZull said...

Nice tutorials,how about in PHP language?It possible PHP can do this trick?

Suresh Dasari said...

hi theZull,
i think we can do the same thing in PHP also but i don't ahve idea on PHP

Anonymous said...

Thanks a lot......!

David said...

Brilliant! Thanks for the tutorial, this is exactly what I was after :)

bhanu said...

Hi how to display the gridview column in dropdownlist how to show?dropdownlist already loaded with some values

Anonymous said...

Thank u dear.

Anonymous said...

The whole is refreshing when we save the data.there is any option not to refresh the whole page.

Anonymous said...

I tried this code by wrapping it in Updatepanel and not able to get pop up.
Can you tell me

Ankur Rana said...

Excellent Artical...

Sunaina said...

Thanks alot .This artical is really very usefull

Anonymous said...

Thank you so much for the help

Anonymous said...

very nice article.
How can I create a template user control?
Thanks a lots

Anonymous said...

perfect example thanks

Rich W said...

Great article. I had given up on doing this when I accidentally came across this site. It works great!

Here's one thing that might help some people. Since I didn't use the sample code directly but instead applied it to my existing code, I ran into an issue where the panel wouldn't appear. I created a button that for the TargetControlID that I didn't want to be visible and I instead showed the popup after some server-side code by using modalname.show (where modalname is the name of the AJAX control). However, if I made the button invisible, the popup panel was visible. If I made the popup panel invisible, it wouldn't popup.

I finally noticed in the sample code that the button control had style="display:none" in it. When I added this and made the button and panel visible, the code worked perfectly.

Thanks.

Anonymous said...

its good

RaViNdRa PaRcHa said...

Perfectly running code...and amazing solution ....fantastic.

RaViNdRa PaRcHa said...

Perfectly running code...and amazing solution ....fantastic.

Anonymous said...

Nice work indeed. Came in very handy as I am 2 weeks into a 3 month trial on a new job and 'needed' to get this modal edit thing working.

Anonymous said...

@>> I tried this code by wrapping it in Updatepanel and not able to get pop up.

I put mine in an Updatepanel and it worked fine. The start of my update panel is directly above the grid and it is closed directly under the panel's closing tag.

Anonymous said...

What if I need more complicated logic.
- gridview with image button
- image button opens modal window with another gridview or listview (some list with links)
- and only click on this link opens edit form in the same modal window

Skittery Jim said...

Where's the demo data

Anonymous said...

thanks
sri

Anonymous said...

Gud JOB Dude...

Anonymous said...

Hai Suresh,

Your work is very usefull to us to develop an good Web Applications

Anonymous said...

Спасибо чувак

Sivanarayana said...

Excellent man..

Thanks alot.

Anonymous said...

I want your SampleDB file used for this source code.Please help me...

Anonymous said...

thank u very much

abhinav bajpai said...

Hi suresh,great job thank you so much for your great support for beginners like me.but please provide some examples using class libraries ...thanks

Anonymous said...

When I am writing this code on a page with master page, then this code is not working. Please help me!
My emailID : sonali16@rediffmail.com

jos - central de reservas said...

Life makes me laugh.
I found this article and wrote this comment on the first article anniversary, jojojo.

THANK YOU VERY MUCH Suresh Dasari, you must know that from now your blog will be in my favorites.

rashmi said...

i had used this code but my updated data doesnt display at page....when i update data will deleted at gridview but it updated in database

Anonymous said...

it is owesome sir ...u will do a great job

Naresh said...

Hi Suresh, very good article..I used in my project.. How can we validate modelpopup with required field validator?
Regards
Naresh

Anonymous said...

Excellent Article Man...Thank You So Much<3

Anonymous said...

Well Done.
Thankyou.

Anonymous said...

Thank you

Anonymous said...

Excellent

Unknown said...

what ever you have written,that code only written by me but grid is not visible on the page so,what can do please helpme

Help said...

I want to Insert page That type of example give me pls

Help said...

I want to Insert page That type of example give me pls

Help said...

Give same type of example insert also,

Ankit Jain said...

Fundoo... superb....

Anonymous said...

hi!
tanx for your valuable tutorial
i have a little problem:
when i try to click on the update image button, i receive this error from compiler:
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
and it refer to the line that u wrote:
lblID.Text = gvdetails.DataKeys[gvrow.RowIndex].Value.ToString ();

please help me. I really need this
thank u so much

K-FeE said...

Chingo, muy buen ejemplo, me estaba dando por vencido hasta que leí este artículo, no puedo creer que sencillo era.

Buen trabajo amigo

navya said...

Hi how to display the gridview column in dropdownlist how to show?dropdownlist already loaded with some values

Jyoti said...

In fact this code is very good. Suresh can u give me one more help. I need to open a folder by clicking a linkbutton. The folder lies in d drive of the computer where the asp.net application is hosted. the same is running in the run time, but if the applicaiton is published, access denied error is coming. Can u please guide I am using Win 7 OS and IIS 7.

Unknown said...

Why the panel is not showing in the html design view

Anonymous said...

Great article! Thank you!

Unknown said...

how this achieve using jquery

Unknown said...

this code is working fine. Bur what about that cancel button. i have one problem when i clicks on Cancel button of popup window,after that when i clicked on edit button it doesn't show popup window again.

Anonymous said...

funny how everyone is an engineer now

Anonymous said...

hello,

I am using your code with ItemTemplate and I am able to show modelpopu with the ID but not other details in the text box. If I fill out the blank text box it is updating the database field and I can see that change in the Gridview. I think I am missing something to populate the textbox value. Here is the code I am using.

protected void imgbtn_Click(object sender, ImageClickEventArgs e)
{

ImageButton btndetails = sender as ImageButton;
GridViewRow gvrow = (GridViewRow)btndetails.NamingContainer;
lblID.Text = GridViewDetails.DataKeys[gvrow.RowIndex].Value.ToString();
txtfname.Text = gvrow.Cells[1].Text;
txtlname.Text = gvrow.Cells[2].Text;
txtDept.Text = gvrow.Cells[3].Text;
txtRequestStatus.Text = gvrow.Cells[4].Text;
this.ModalPopupExtenderEdit.Show();
//sconn.Close();

}

Unknown said...

hi suresh little bit problem

error are :- Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. The system cannot find the file specified.

Unknown said...

This is wwesome code, it does exactly what I wanted.

I would like to have paging controls and sorting controls on the gridview.

Can you help ??

DURGA PRAKASH said...

Thanks dude

Ajay said...

If i have the image field in gridview than how can i update the image in gridview using modal popupextender.

Please give your valuable suggestion.

Imi Chitterman said...

Your sharing is always useful
thanks

gnosys said...

Great work, this is even better than jQuery's blockUI - thanks!

Anonymous said...

Nice One, Thanks...

Imi Chitterman said...

Hi Suresh,
Comment ID 60 above is an issue that I also encountered. Please have you any idea why this happens with the pop up.
Regards

Imi Chitterman said...

Hi Suresh,
Issue 60 only work when we use


and not template items

Anonymous said...

tanx a lot.....

Anonymous said...

hii this is code is working fine with boundfields but its not working with templatefiels..

what's the difference between templatefield and boundfield..

thnx in advance

Anonymous said...

Hi Frnd it's working great Thank's lot....................

Gaurav Agarwal said...

nice article!!!!

varun said...

when i run this in internet explorer popup will not show...pls help.......

Anonymous said...

how to display gridview controls other than BoundField, i.e. CheckBoxField?

Anonymous said...

i have my gridview bind from backend which i want to display in popup area....but unfortunately it isnot supporting gridview...what is the solution of this?

Unknown said...

Is it possible to open popup and render data in controls without pageload using some js or jquery code.

Unknown said...

good article..working fine..
But whenever we press the back button of browser the pop up reappears.
Please help I have included this in my project and it is looking great but only this demerit.

Also what if there is one more column in this database called description which is not shown in grid but we want it to appear in pop up so that we can edit it there.
I have fetched the description column in the pop up panel through datareader but when i edit it the changes are not made.
Please help Me!

Anonymous said...

hi sir,
i use your coding for selecting the grdview row, and i want to populate in popup window instead of using modal popup extender i used your simple jquery popup coding, in that, problem i faced was popwindow was shown but the selected datas are not shown sir help me for this issue

Anonymous said...

when i used radio button in panel then radio button event not fire when i run my webpage in internet exp.......

ravi said...

it is very appreciating.

Anonymous said...

It is So helpful...........

Anonymous said...

Hello ,

Anonymous said...

I have bind second dropdownlist on the selection of first ... after saving record at the time of update second dropdownlist value is not set ... please help me..

Anonymous said...

how to redirect from one page to other page when i click any button in modal popup page .
response.redirect in not working

Unknown said...

hi..suresh
give me code for dropdown with checkboxlist in gridview on click imagebutton(down-Errow) and after hide...thanks..

Anonymous said...

nice :)

Bvenkat Jeewesh said...

nice blog :-)

Anonymous said...

sir superb very nice....:) ... I have to search database and display in gridview by using 4 dropdown and 1 checkbox.....but only 3 dropdown values are displaying please give me your reply...

Anonymous said...

good one. helped me.

Anonymous said...

Good Sample.Helped Me.

Unknown said...

i tried this but after run the page it shows empty page in web browser.please help me any one.

Nitin said...

Nice Demo.I tried this in my project but still Pop was not displayed. Popup works when I used hidden button instead of image button in grid.

Anonymous said...

Hello, I'm a newer in ASP.NET, and very intested this codes, but I can't download the source codes. Why?

Unknown said...

hello sir,
Its nice article, I have a problem, I need to open another page as popup on button click. Can I do that using jquery ? N how?

Unknown said...

I got the following error while update the grid using popup....

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Unknown said...

How to add validations in popup while update

Sid said...

Unable to download the source code file. This download button in the other tab does not contain any link.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.