Hello fellow programmers, got a few problem here. I am adding a user control inside a gridview.
Now my question is how can bind it cause inside the user control is a gridviewthat needs the CourseCatID so that it could bind the datas. And by the way I cannot use nested griview cause I need the render of the nested usercontrol for another purpose. Any tutorial/help will be gladly appreciated.
<asp:GridView ID="grdCategory" runat="server" AutoGenerateColumns="False" Width="1100px"
DataKeyNames="CourseCatID" Font-Names="verdana,arial,helvetica,sans-serif" Font-Size="8pt"
CellPadding="4" ForeColor="#333333" GridLines="None">
<Columns>
<asp:ButtonField Text="SingleClick" CommandName="SingleClick" Visible="False" />
<asp:BoundField HeaderText="CourseCatID" Visible = "false" DataField="CourseCatID" />
<asp:TemplateField HeaderText="Course Category">
<ItemTemplate>
<asp:Label ID="lblCourseCatID" runat="server" Visible="false" Text='<%# Eval("CourseCatID")%>'></asp:Label>
<a href="javascript:toggleDiv('mydiv<%# Eval("CourseCatID")%>')">
<asp:TextBox ID="txtCourseCatName" runat="server" Text='<%# Eval("CourseCatName") %>' Font-Size="XX-Small"
Font-Names="Verdana" Width="300px" Visible="false"></asp:TextBox>
<asp:Image ID="img" onclick="javascript:Toggle(this);" runat="server" ImageUrl="~/Images/minus.gif"
ToolTip="Collapse" Width="7px" Height="7px" ImageAlign="AbsMiddle" /></a>
<asp:Label ID="lbllastname" Height="15px" runat="server" Text='<%# Eval("CourseCatName")%>'> </asp:Label>
<div id="mydiv<%# Eval("CourseCatID")%>">
<br />
      <%--OnClick="ImageAdd_click" --%>
<asp:ImageButton ID="ImageAdd" Height="17px" ImageUrl="Images/addCourse.png" runat="server"
CommandName="cmdAdd" CommandArgument='<%# Eval("CourseCatID") %>' />
<br />
<br />
      
<asp:Panel ID="pnlCourse" runat="server"></asp:Panel>
<b><cuc1:CourseUserControl ID="CourseUserControl1" runat="server" /></b>
<br />
<br />
<br />
<br />
</div>
</ItemTemplate>
</asp:TemplateField>
Thank you for your time
You have a couple of options.
The easiest one is to expose a public property on the user control that will let you do this:
<cuc1:CourseUserControl ID="CourseUserControl1" runat="server" CourseCategoryID='<%# (int)Eval("CourseCatID") %>' />
Then databind in the user control as soon as that property is assigned to. Note that I'm assuming the category is an Int32. For example (note that the CourseCategoryID stores its value in a private field, not in ViewState):
private int _courseCategoryID;
public int CourseCategoryID
{
get { return _courseCategoryID; }
set
{
_courseCategoryID = value;
// TODO: code that initializes the GridView in user control.
this.DataBind();
}
}
Your other option is to expose the same property and handle the RowDataBound event and do this:
if (e.Row.RowType == DataControlType.DataRow)
{
CourseUserControl courseDetails;
courseDetails = (CourseUserControl)e.Row.FindItem("CourseUserControl1");
// Assuming category ID is Int32
courseDetails.CourseCategoryID = (int)grdCategory.DataKeys[e.Row.RowIndex].Value;
courseDetails.DataBind();
}
Note that I'm databinding manually instead of immediately after assigning a new category to the user control in the current row.
For more information, see:
GridView.RowDataBound Event (ASP.NET 3.5)
or
GridView.RowDataBound Event (ASP.NET 4.0)
Related
I have reapeater in my code and trying to validate the textbox using asp.net required field validator. But validation messsage
not displaying, i opened the developer tools and found that style="visibility:hidden" added into the required field validator.
Below is my code
<asp:Repeater ID="RepeaterCategory" runat="server" DataSource='<%# this.Categories.Count==0 ? null : this.Categories %>'>
<ItemTemplate>
<div>
<asp:Label runat="server" Visible="true" Text="Category" />
<asp:PlaceHolder runat="server" Visible="true">
<asp:TextBox ID="txtCategoryID" runat="server" value="1" />
<asp:TextBox ID="txtCategoryName" runat="server" value="<%# (Container.DataItem as Category).Name %>" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="<br/>This is a required field" ControlToValidate="txtCategoryName" ValidationGroup="NewCategoryGroup"></asp:RequiredFieldValidator>
</asp:PlaceHolder>
<asp:LinkButton runat="server" ToolTip="Save" ValidationGroup="NewCategoryGroup" OnClick="SaveCategory_Click"><img src='<%# some path%>/images/save.gif' /></asp:LinkButton>
<asp:LinkButton runat="server" ToolTip="Close" OnClick="CloseCategory_Click"></asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
Code behind file
protected void SaveCategory_Click(object o, EventArgs e)
{
Page.Validate("NewCategoryGroup");
if (!Page.IsValid)
return;
//logic
}
Can anyone suggest how to enable it?
The style="visibility:hidden" is default behavior. It changes to style="visibility: visible;" when the error message needs displaying. Therefore you probably don't have an error.
The validator is a 'RequiredFieldValidator', and since the textbox that is being validated is already filled with the value "TestCategory" there are no errors. If you just add text to the Save button (which has no ID tag) so that it becomes visible, remove the value from the txtCategoryName textbox and click the save button you will see the error message.
This works:
<asp:TextBox ID="txtCategoryName" runat="server" value="" />
<asp:RequiredFieldValidator runat="server" ErrorMessage="<br/>This is a required field" ControlToValidate="txtCategoryName" ValidationGroup="NewCategoryGroup"></asp:RequiredFieldValidator>
<asp:LinkButton runat="server" ToolTip="Save" ValidationGroup="NewCategoryGroup" OnClick="SaveCategory_Click" ID="LinkButton1">Save Me!</asp:LinkButton>
You don't need this code
Page.Validate("NewCategoryGroup");
if (!Page.IsValid)
Another advantage is that the validators work now without a postback, this saves a roundtrip to the server.
And ALWAYS do server side validation also, but try to do the first validation without postback.
UPDATE
What you want is probably validation per item. And since your validationgroup is always the same it will fire for all textboxes. Try this:
<asp:Repeater ID="RepeaterCategory" runat="server">
<ItemTemplate>
<div>
<asp:TextBox ID="txtCategoryName" runat="server" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>' Text='<%# Eval("Category") %>' />
<br />
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ErrorMessage="This is a required field<br />" ControlToValidate="txtCategoryName" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>'></asp:RequiredFieldValidator>
<asp:LinkButton runat="server" ValidationGroup='<%# "myVal_" + Container.ItemIndex %>' OnClick="Button1_Click" ID="LinkButton1">Save Me!</asp:LinkButton>
</div>
</ItemTemplate>
</asp:Repeater>
I need to show an AjaxControlToolkit ModalPopupExtender control, when user checks/unchecks a CheckBox control that is inside a GridView as a TemplateField.
-- Updated on 24/05/2013
See final solution here...
We finally solved the problem. So I decided to post here the complete solution and the final code.
The GridView
<asp:GridView ID="gvDocs" runat="server" CssClass="grid" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="gvDocs_PageIndexChanging"
OnSorting="gvDocs_Sorting"
OnRowDataBound="gvDocs_RowDataBound">
<AlternatingRowStyle CssClass="grid_row_alternate"/>
<HeaderStyle CssClass="grid_header" />
<RowStyle CssClass="grid_row" />
<SelectedRowStyle CssClass="grid_row_selected" />
<Columns>
<asp:BoundField DataField="ID"/>
<asp:BoundField DataField="COLUMN_A" SortExpression="COLUMN_A" HeaderText="COLUMN_A" />
<asp:BoundField DataField="COLUMN_B" SortExpression="COLUMN_B" HeaderText="COLUMN_B" />
<!-- TemplateField with the CheckBox and the ModalPopupExtender controls -->
<asp:TemplateField HeaderText="Check" SortExpression="CHECK_COLUMN">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
<!-- Modal Popup block -->
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" BackgroundCssClass="modalBackground" DropShadow="True" TargetControlID="CheckBox1" PopupControlID="panModalPopup" CancelControlID="CancelButton"/>
<asp:Panel ID="panModalPopup" runat="server" style="display:none; text-align:left; width:400px; background-color:White; border-width:2px; border-color:#40A040; border-style:solid; padding:10px;">
Are you sure?
<br /><br />
<div style="text-align:right;">
<asp:Button ID="ConfirmButton" runat="server" Text="Confirm" OnClick="ConfirmButton_Click" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ID") %>'/>
<asp:Button ID="CancelButton" runat="server" Text="Cancel"/>
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
The code behind
protected void gvDocs_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
// Setting the CheckBox check reading the state from DB
CheckBox CheckBox1 = (CheckBox)e.Row.FindControl("CheckBox1");
CheckBox1.Checked = DataBinder.Eval(e.Row.DataItem, "CHECK_COLUMN").ToString() == "Y"; // Or any other value that works like true/false
}
}
protected void ConfirmButton_Click(object sender, EventArgs e)
{
string id = ((Button)sender).CommandArgument; // Get the ID column value
// Update the CHECK_COLUMN value on the DB or do whatever you want with the ID...
BindData(); // Method that do the GridView DataBind after the changes applied to the DB
}
Some things to know
1) The ModalPopupExtender1 control is inside the GridView TemplateField because it needs to have access to the CheckBox1 and its click event. It's probably not the best solution ever, but it works and so it would not affect to much on performance if your GridView is not too complicated and if it is paged.
2) In order to catch the ConfirmButton Click event, you have to remove the OKControlID property from the ModalPopupExtender control settings.
-- END
-- Updated on 22/05/2013
Then I need the ID of the corresponding row to make an UPDATE on the DB.
-- END
This is the GridView
<asp:GridView ID="gvDocs" runat="server" CssClass="grid" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="gvDocs_PageIndexChanging"
OnSorting="gvDocs_Sorting"
OnRowDataBound="gvDocs_RowDataBound">
<AlternatingRowStyle CssClass="grid_row_alternate"/>
<HeaderStyle CssClass="grid_header" />
<RowStyle CssClass="grid_row" />
<SelectedRowStyle CssClass="grid_row_selected" />
<Columns>
<asp:BoundField DataField="ID_DOCUMENTO" Visible="False"/>
<asp:BoundField DataField="NUM_PROT" SortExpression="NUM_PROT" HeaderText="N. Prot." />
<asp:BoundField DataField="DATE_PROT" SortExpression="DATE_PROT" HeaderText="Data Prot." />
... some other BoundFields ...
<asp:TemplateField HeaderText="Da archiviare" SortExpression="DA_ARCHIVIARE">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="chkArchiviare" runat="server" AutoPostBack="True" OnCheckedChanged="chkArchiviare_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
And this is the ModalPopup block
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True" TargetControlID="panModalPopup" PopupControlID="panModalPopup" OkControlID="btnConferma" CancelControlID="btnAnnulla" />
<asp:Panel ID="panModalPopup" runat="server" style="display:none; width:400px; background-color:White; border-width:2px; border-color:Black; border-style:solid; padding:20px;">
Are you sure?
<br /><br />
<div style="text-align:right;">
<asp:Button ID="btnConferma" runat="server" Text="Conferma" OnClick="btnConferma_Click"/>
<asp:Button ID="btnAnnulla" runat="server" Text="Annulla" OnClick="btnAnnulla_Click" />
</div>
</asp:Panel>
Now, I want to show the ModalPopup each time a checkbox is checked/unchecked and that popup have to show a confirmation message with 2 buttons: Confirm and Cancel.
Confirm have to do an update on the DB and then postback.
Cancel have only to hide the popup without postback.
I know that ModalPopupExtender listens to OnClick events. So, do I necessary need a Button, LinkButton, ImageButton, etc. or can I do what I want?
You are right, it listens to onclick events, but client-side ones, so, the target control of the extender can be anything you can click on, even a div or a label.
try to show/hide ModalPopupExtender1 from chkArchiviare_CheckedChanged event like this.
ModalPopupExtender1.show();
and
ModalPopupExtender1.hide();
take one Hidden button and make it as TargetControlID like this.
<asp:HiddenField ID="btnHiddenDtl1" runat="Server" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True" TargetControlID="btnHiddenDtl1" PopupControlID="panModalPopup" OkControlID="btnConferma" CancelControlID="btnAnnulla" />
you need not to call cancel button click event to hide ModalPopupExtender1.
You no need to include ModalPopup Extender inside your GridView. You can bind check box control in template field in GridView and use OnCheckedChanged property in it...So template would be like below
<asp:TemplateField HeaderText="Da archiviare" SortExpression="DA_ARCHIVIARE">
<ItemStyle HorizontalAlign="Center"/>
<ItemTemplate>
<asp:CheckBox ID="chkArchiviare" runat="server"
OnCheckedChanged="chkArchiviare_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>
After this you have to call show function on chkArchiviare_CheckedChanged event...like this
ModalPopupExtender1.Show();
Here ModalPopupExtender1 is ID of you ModalPopupExtender control.
One more thing you have to remember use one button on .aspx page. And pass this button ID into ModalPopupExtender TargetControlID... Like this
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DropShadow="True"
TargetControlID="btnShowModalPopup" PopupControlID="panModalPopup"
OkControlID="btnConferma" CancelControlID="btnAnnulla" />
<asp:Panel ID="panModalPopup" runat="server" style="display:none; width:400px;
background-color:White; border-width:2px; border-color:Black; border-
style:solid; padding:20px;"> Are you sure?<br /><br />
<div style="text-align:right;">
<asp:Button ID="btnConferma" runat="server" Text="Conferma"
OnClick="btnConferma_Click"/>
<asp:Button ID="btnAnnulla" runat="server" Text="Annulla"
OnClick="btnAnnulla_Click" />
</div>
</asp:Panel>
Here Why Iam using this button?....There is no use of this button because we are using show() in codebehind...but if we are not pass button Id to ModapPopupExtender TargetControlId property. It will give you an error.
So using ModalPopupExtender in this way...you can use it with LinkButton, Label, Button. For more details with example, you can check the below link....
How to Use ModalPopup Extender into GridView
I hope this article will clear your all doubts....Enjoy and share this with others...Thanks!
ASP.net(C#), VS2010, Win 7.
New to WebDev, so this might be a simple syntax thing but here it goes...
Long story short I have to force a postback on a GridView that shows attachments I upload using an ASPxUploadControl. I put the GridView inside an ASPxCallbackPanel and am trying to get my GridView to update on the page after an attachment is uploaded using ASPxCallbackPanel.PerformCallback();
Here's the Upload control, in its' ClientSideEvent is where I'm trying to call the clientSideEvent from the Button shown below. Just trying to force a button click really, but I tried doing it from the code-behind but that didn't work. Any help would be appreciated!
<dxuc:ASPxUploadControl ID="FileUpload1" runat="server"
ClientInstanceName="uploader"
ShowAddRemoveButtons="False"
ShowUploadButton="True"
AddUploadButtonsHorizontalPosition="Center"
AddUploadButtonsVerticalPosition="Top" FileInputCount="1"
UploadMode="Advanced"
OnFileUploadComplete="UploadControl_FileUploadComplete"
Size="30">
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.Click; }" />
<%-- <AdvancedModeSettings EnableMultiSelect="True" /> "does not have public property named "advancedModeSettings" version is too old--%>
<ValidationSettings
AllowedFileExtensions=".doc,.pdf,.xls,.txt,.jpeg,.jpg,.gif,.png,.oft,.htm,.html,.mht,.rtf,.zip"
MaxFileSize="5242880"
FileDoesNotExistErrorText="This file can't be found."
GeneralErrorText="Custom file uploading fails due to an external error that doesn't relate to the ASPxUploadControl's functionality"
MaxFileSizeErrorText="Size of the uploaded file exceeds maximum file size">
<ErrorStyle ForeColor="Red"/>
</ValidationSettings>
</dxuc:ASPxUploadControl>
Here is the GridView as well as a button I made that successfully refreshes the grid.
<div>
<dxe:ASPxButton ID="ASPxButton1" runat="server" ClientInstanceName="Button1" Text="Reload Panel" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {ASPxCallbackPanel1.PerformCallback(); e.processOnServer = true;}" />
</dxe:ASPxButton>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel1" runat="server"
ClientInstanceName="ASPxCallbackPanel1" Width="492px"
Height="100%">
<PanelCollection>
<dx:PanelContent runat="server">
<asp:GridView ID="gvAttachment" SkinID="grid" runat="server" Width="98%"
OnRowDataBound="AttachmentControl_OnRowDataBound"
meta:resourcekey="gvAttachResource1"
PagerSettings-FirstPageText="<%$ Resources:CommonControlText,FirstPageText %>"
PagerSettings-LastPageText="<%$ Resources:CommonControlText,LastPageText %>"
PagerSettings-PreviousPageText="<%$ Resources:CommonControlText,PreviousPageText %>"
PagerSettings-NextPageText="<%$ Resources:CommonControlText,NextPageText %>"
AutoGenerateColumns="False">
<EmptyDataRowStyle CssClass="emptyData" />
<EmptyDataTemplate>
<table class="usercontroldetail container_table">
<tr>
<td class="tdlayout">
<asp:Label ID="Localize1" runat="server">
<%= Placeholder %>
</asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="AtchmtId" HeaderText="Attachment ID"
visible = "false" meta:resourcekey="BoundFieldResource1">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField ="FileNm" HeaderText="File Name" />
<asp:BoundField DataField="UsrNm" HeaderText="Uploaded By"
/>
<asp:BoundField DataField="AtchmtDt" HeaderText="Date"
/>
<asp:BoundField DataField="FileSizeCnt" HeaderText="File Size"
/>
<asp:TemplateField AccessibleHeaderText="Actions" HeaderText="Actions">
<ItemTemplate>
<div style="text-align:center;">
<asp:LinkButton ID="btnDelete" Visible="False" runat="server"
ToolTip="Delete Selected Attachment"
OnClick="btnDelete_Click"
Text="Delete" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnDeleteResource1" />
<asp:Label ID="lblPipe" runat="server" Text="|" />
<asp:LinkButton ID="btnView" Visible="False" runat="server"
ToolTip="View Selected Attachment"
OnClick="btnView_Click"
Text="View" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnViewResource1" />
</div>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
</Columns>
<%--<PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next >" PreviousPageText="< Previous"></PagerSettings>--%>
<RowStyle CssClass="row_odd" />
<AlternatingRowStyle CssClass="row_even" />
</asp:GridView>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
FYI: The GridView is getting the new attachment put in it. I'm just not seeing it on the page because the UploadControl only updates itself.
Edit:Figured it out just used the OnClick() method as below. Derp. Forgot that the ASPx button inherited all the ASP buttons methods. But now my original plan of making the button invisible seems to be foiled. When Button1.OnClick() is called with the Visible property for the Button set to "false". it says Button1 is not defined. Anyway around this?
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.OnClick(); }" />
If I got you right, you can manipulate the behavior of all update panels on page via property called a updateMode (Conditional, Always). Changing one updatepanel will cause refreshing of all, if all have mode set to Always.
I have a datalist in vb web form.
How can i get the value in a specific rows and cells of a datalist?
I could do it for detailsview but how to do it for datalist??
Below is my code for detailsview:
Dim selectedCommentAns As String = DetailsView.Rows(0).Cells(1).Text
I tried the same way for datalist but it dont have rows and cells to be selected.
This is the asp markup of my datalist:
<asp:DataList ID="DataListPhotoGallery" runat="server" CellPadding="5"
CellSpacing="12" DataKeyField="PhotographerPhotoId"
DataSourceID="SqlDataSourcePhotoGallery" RepeatColumns="3">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" BorderColor="#C7B273"
BorderStyle="Groove" BorderWidth="12px" Height="200px"
ImageUrl='<%# Eval("PhotographerPhotoImgPath", "images/UserUploadedPhoto/{0}") %>'
Width="220px" />
<br />
Photo No:
<asp:Label ID="PhotographerPhotoIdLabel" runat="server"
Text='<%# Eval("PhotographerPhotoId") %>' />
<br />
Photo Description:
<asp:Label ID="PhotographerPhotoDescLabel" runat="server"
Text='<%# Eval("PhotographerPhotoDesc") %>' />
<br />
Photo Name:
<asp:Label ID="PhotographerPhotoImgNameLabel" runat="server"
Text='<%# Eval("PhotographerPhotoImgName") %>' />
<br />
Photographer Name:
<asp:Label ID="PhotographerIdLabel" runat="server"
Text='<%# Eval("PhotographerName") %>' />
<br />
<asp:Button ID="AddCommentBtn" runat="server"
CommandArgument='<%# Eval("PhotographerPhotoId") %>' Font-Bold="True"
Font-Size="Medium" onclick="AddCommentBtn_Click" Text="Add Comment" />
<asp:Button ID="Button2" runat="server"
CommandArgument='<%# Eval("PhotographerPhotoId") %>' Font-Bold="True"
Font-Size="Medium" onclick="Button2_Click" Text="Order Photo" />
<br />
Instead of Rows and Cells, DataList has a property named Items that lets you access its collection of data-bound items:
Dim itemIndex As Integer = 9
Dim label As Label = DataListPhotoGallery.Items(itemIndex).FindControl("PhotographerPhotoIdLabel")
Dim text As String = label.Text
If you know the row and column indexes but not the item index, then you can calculate the item index like this:
If RepeatDirection is Horizontal: itemIndex = rowIndex * RepeatColumns + columnIndex
If RepeatDirection is Vertical: Post a comment if you need this because it's rather complicated.
You can access items using
DataListPhotoGallery.Items
If you want to access specific item, the you need to find object you are looking for. In this case you want to get a value of PhotographerPhotoIdLabel label.
var PhotographerPhotoIdLabel = DataListPhotoGallery.Items[itemsId].FindControl("PhotographerPhotoIdLabel") as Label;
var yourString = PhotographerPhotoIdLabel.Text;
Hope that helps
You can use the concern datasource to get the value. Please refer the below code to get the required value.
Dim dv As DataView
dv = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
selectedCommentAns = dv.Table.Rows[0][1]
Hope this will help.
I have GridView on my asp.net page, one column in that grid is ImageButton (TemplateField with ID="imbReserve"). On click on that button I want to show PopUp, but when I put TargetControlId="imbReserve" I get error message " A control with ID 'imbReserve' could not be found". How to achieve this, on click on button inside Grid show PopUp ?
Have a look at these 2 articles, that just helped me out with this problem
Article 1: A More Traditional approach
The Following is paraphrased from the above article
The Page Code:
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
Width="95%">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="customerid" HeaderText="ID" />
<asp:BoundField DataField="companyname" HeaderText="Company" />
<asp:BoundField DataField="contactname" HeaderText="Name" />
<asp:BoundField DataField="contacttitle" HeaderText="Title" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="pnlPopup" PopupControlID="pnlPopup"
CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
[Your Content Here]
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width:95%">
<asp:Button
ID="btnSave" runat="server" Text="Save" />
<asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
</div>
</asp:Panel>
Note that the GridView is wrapped in an update panel also that the Target Control ID for the Modal Extender is the same as the Pop Up Control ID. This is because the ModalPopUp Extender needs a target control ID and I think this solution is a better plan than using a hidden button.
Now For the Code Behind:
protected void BtnViewDetails_Click(object sender, EventArgs e)
{
// Do Anything you need to the contents of the update panel
// update the contents in the detail panel
this.updPnlCustomerDetail.Update();
// show the modal popup
this.mdlPopup.Show();
}
Article 2:Uses Clientside Javascript
The Following is paraphrased from the above article
The client side Javascript
<script type="text/javascript">
// keeps track of the delete button for the row
// that is going to be removed
var _source;
// keep track of the popup div
var _popup;
function showConfirm(source){
this._source = source;
this._popup = $find('mdlPopup');
// find the confirm ModalPopup and show it
this._popup.show();
}
function okClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// use the cached button as the postback source
__doPostBack(this._source.name, '');
}
function cancelClick(){
// find the confirm ModalPopup and hide it
this._popup.hide();
// clear the event source
this._source = null;
this._popup = null;
}
Page Code:
<asp:GridView ID="gvToDoList" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Item" HeaderText="Description" />
<asp:BoundField DataField="IsCompleted" HeaderText="Complete?" />
<asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px" >
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server"
OnClientClick="showConfirm(this); return false;"
OnClick="BtnDelete_Click" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<ajaxToolKit:ModalPopupExtender BehaviorID="mdlPopup" runat="server"
TargetControlID="div" PopupControlID="div"
OkControlID="btnOk" OnOkScript="okClick();"
CancelControlID="btnNo" OnCancelScript="cancelClick();"
BackgroundCssClass="modalBackground" />
<div id="div" runat="server" align="center" class="confirm" style="display:none">
<img align="absmiddle" src="Img/warning.jpg" />Are you sure you want to delete this item?
<asp:Button ID="btnOk" runat="server" Text="Yes" Width="50px" />
<asp:Button ID="btnNo" runat="server" Text="No" Width="50px" />
</div>
Again note that the Target Control ID for the Modal Pop Up Extender is the same as the Pop Up Control ID. Also note the OnClientClick attribute on the button in the template field, make sure your include "return false;".
All that is needed in the code behind it the onClick (or onCommand) event handler to do what you need to do.
I've tried both of these approaches successfully.
Hope one of these two works for you.
The problem is related to the fact that the real ID is getting changed when the page get rendered to the client.
Open your page source in the browser and look at the ID that is generated from asp.net. Then use that ID inside the TargetControlID property
This kind of problem is present with all the templated controls in ASP.NET
A cleaner way will be to bind the TargetControlID property of the ModalPopupExtendr on Page Load where you can use the ClientID property dinamically generated
modalPopupExtender.TargetControlID = myTemplateControl.ClientID;