Dropdownlist in a repeater, selected index changed not working - asp.net

I have a repeater with a dropdownlist in it. When a user changes its index, I would like a label to change its value. (the ddlSizes values come from a MySQL DB)
Sizes.aspx
<asp:DropDownList ID="ddlSizes" runat="server" AutoPostBack="True" DataSourceID="objdsSizes" DataTextField="SizeName" DataValueField="SizeID" />
<asp:Label ID="lbldummy" runat="server" Text=""></asp:Label>
Sizes.aspx.vb
Protected Sub ddlSizes_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlSizes.SelectedIndexChanged
lbldummy = ddlSizes.value
End Sub
But the ddlSizes.SelectedIndexChanged isn't recognized. So the value of lbldummy won't change.
Any suggestions? Thank you.

You will want to create the handler for the DropDownList, within this you need to have code which will convert the sender into a DropDownList then get the parent control and convert it into the RepeaterItem. From this you can then reference any other controls within the RepeaterItem
Public Sub ddlSizes_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim ddlSizes As DropDownList = DirectCast(sender, DropDownList)
Dim ri As RepeaterItem = DirectCast(ddlSizes.Parent, RepeaterItem)
Dim lbldummy As Label = DirectCast(ri.FindControl("lbldummy"), Label)
lbldummy.Text = ddlSizes.SelectedValue
End Sub
Then on your ddlSizes DropDownList add OnSelectedIndexChanged="ddlSizes_SelectedIndexChanged" and make sure it has AutoPostBack="True" set

Text is probably the default property, but I'd still specify it:
lbldummy.Text = ddlSizes.value
but for this, you really don't need to do a postback, you can accomplish this through Javascript as well. doing something like this:
<asp:DropDownList ID="ddlSizes" runat="server" onchange="return ddlSizes_change(this);" DataSourceID="objdsSizes" DataTextField="SizeName" DataValueField="SizeID" />
function ddlSizes_change(dropdown)
{
document.getElementById('<%= lbldummy.ClientID %>').innerHTML =
dropdown.options[myindex].value
return true;
}

Here's an example (C# but easily adaptable to VB.NET). Notice how inside the DdlSizes_SelectedIndexChanged I use FindControl to find the corresponding label:
<%# Page Language="C#" %>
<script type="text/c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rep.DataSource = Enumerable.Range(1, 5);
rep.DataBind();
}
}
protected void DdlSizes_SelectedIndexChanged(object sender, EventArgs e)
{
var ddl = (DropDownList)sender;
var lbl = (Label)ddl.FindControl("lbldummy");
lbl.Text = ddl.SelectedValue;
}
</script>
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<asp:Repeater ID="rep" runat="server">
<ItemTemplate>
<asp:DropDownList ID="ddlSizes" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DdlSizes_SelectedIndexChanged">
<asp:ListItem Value="1" Text="item 1" />
<asp:ListItem Value="2" Text="item 2" />
<asp:ListItem Value="3" Text="item 3" />
</asp:DropDownList>
<asp:Label ID="lbldummy" runat="server" />
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>

Related

I can't access the ID nested inside the ListView <itemtemplate>

I am trying to grab the value of the checkbox every time a user checks it using the following markup:
<!---- <asp:CheckBoxList ID="CheckboxWattage" runat="server" RepeatColumns="1" CellSpacing="-1" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right" Width="300px">
<asp:ListItem text="" value=""></asp:ListItem>
</asp:CheckBoxList>--->
<asp:Listview id="filterListView" runat="server" DataSourceID="" onitemdatabound="filterListView_ItemDataBound" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" value='<%#DataBinder.Eval(Container.DataItem,"UDF_WATTAGE") %>' runat="server"/>
<asp:label ID="LabelValue" AssociatedControlID="CheckBox1" runat="server" text='<%#Eval("UDF_WATTAGE") %>' ></asp:label>
<asp:label Style="font-size:12px; font-style: italic;" ID="countLabel" runat="server" text='<%# "(" + DataBinder.Eval(Container.DataItem,"CountofUDF_WATTAGE") +")" %>' ></asp:label>
</br>
</ItemTemplate>
</asp:Listview>
<asp:Button id="wattagebtn" text="Apply" class="btn btn-danger" style="float:right;" onclick="wattageApply_Click" runat="server"></asp:Button>
<asp:Label ID="Label1" runat="server" Text="hi"></asp:Label>
</div>
</div>
code behind update! I think I was able to grab the CheckBox1 ID. how can I grab the checkbox value? When checked?
I will update once I find the solution for anyone that's having the same issue.
UPDATEEE FOUND THE SOLUTION. i had to put if(!IsPostBack){ }
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dapter.Fill(ds);
filterListView.DataSource = ds;
filterListView.DataBind();
}
protected void filterListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
}
}
protected void wattageApply_Click(Object sender, System.EventArgs e)
{
foreach (ListViewItem item in filterListView.Items)
{
CheckBox cb = item.FindControl("CheckBox1") as CheckBox;
if (cb.Checked == true)
{
string ch;
Label1.Text = cb.Text;
}
else
{
Label2.Text = cb.Text;
}
}
<asp:ListView ID="ListView1" runat="server" DataSourceID="">
<ItemTemplate>
<div>
<asp:CheckBox ID="CheckBox1" runat="server"
OnCheckedChanged="ListViewItemCheckChanged"
Text='<%#DataBinder.Eval(Container.DataItem,"UDF_WATTAGE") %>' />
.
.
.
</div>
</ItemTemplate>
</asp:ListView>
Code Behind (VB.NET):
Protected Sub ListViewItemCheckChanged(sender As Object, e As EventArgs)
Dim cb As CheckBox = sender
// at this point the variable cb contains the user selected checkbox
End Sub
This will allow you to examine the last Checkbox the user clicked
Keep in mind there will be a postback on each click.
This will give you what you are asking for but is probably not the best interface experience for the user.
Typically when presented with multiple check boxes you allow all the user selections and then process the selections with one postback via some submit style button. This would require:
Looping through the ListView's Item Collection,
For each ListViewDataItem find each CheckBox via FindControl("CheckBox1")
Check for CheckBox1.Checked() and act accordingly
Addendum: How to Loop through ListView Items (VB.NET):
Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim cb As CheckBox
For Each lvi As ListViewDataItem In ListView1.Items
cb = lvi.FindControl("CheckBox1")
If cb.Checked Then
...
Else
...
End If
Next
End Sub
Addendum: A word about Checkboxes:
An ASP CheckBox doesn't have a value per se. It's "value" is the Boolean "cb.Checked". But there are two ways you can associate a value with CheckBox
1) If the value is not a security issue and not particulary lengthy you can add an Attribute in the ListView ItemDataBound event
Private Sub ListView1_ItemDataBound(sender As Object, e As ListViewItemEventArgs) Handles ListView1.ItemDataBound
If e.Item.ItemType = ListViewItemType.DataItem Then
Dim drv As DataRowView = e.Item.DataItem
Dim cb As CheckBox = e.Item.FindControl("CheckBox1")
cb.Attributes("some-legal-html-attribute-name") = drv("Some_dataset_field")
End If
End Sub
You are doing something similar with this in your aspx:
<asp:CheckBox ID="CheckBox1" runat="server"
value='<%#DataBinder.Eval(Container.DataItem,"UDF_WATTAGE") %>'/>
the above should render to something like this:
<input id="ListviewMangledprefix_CheckBox1" type="checkbox"
value="[value of UDF_WATTAGE FIELD]" />
Inspect the field in the rendered browser page and see if the "value" attribute is being rendered. If so you should be able to access it in the code behind as:
Dim wattage as String = cb.Attributes("value")
2) Better and more secure would be to implement and use ListView1.DataKeys. But this is a much more extensive topic that you should research when you have time

Gridview inside UpdatePanel on ModalDialog not updating after AsyncFileUpload

I have a GridView inside an update panel, and a AsyncFileUpload (outside the Update Panel) that I am using to upload Images. All these are in a ASPX page called using the SHOWMODALDIALOG.
What I'm tying to achieve:
1. As soon as the file upload completes, the Update Panel updates, and the gridview displays the image the user just added.
The problems I'm facing:
1. The Gridview is not refreshing, even though I have a Databind event after the file is uploaded to the database. The Update Panel is getting refreshed through the __doPostBack('UpdatePanelID',' ') in a JS called by OnClientUploadComplete (I'm checking this through a Label showing current time in the Update Panel)
2. The ModalDialog is opening a new page whenever I click on 'Save Changes' or 'Cancel' button after adding an Image. If I just open the window and click these buttons, they work fine. I did try including <base target="_self" /> in the <head>, and finally settled with window.name="xxx" onload body.
Any help is appreciated.
My code:
ASPX
<%# Page Language="VB" AutoEventWireup="false" CodeFile="RCMT0032.aspx.vb" Inherits="RCWKSHEET.RCMT0032" EnableEventValidation="false"%>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit"%>
<html>
<head>
<base target="RCMT0032" />
<title>RCMT0032</title>
<script type="text/javascript">
function readpasseddata() {
window.name = 'RCMT0032';
var rpt = window.dialogArguments;
document.getElementById("HiddenReport").value = rpt;
}
function UploadComplete(sender, args) {
__doPostBack('gvupd', '');
}
</script>
</head>
<body onload="readpasseddata()" >
<form id="Form1" method="post" runat="server" target="RCMT0032" >
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:AsyncFileUpload id="BrowserHidden" Width="1" runat="server" OnClientUploadComplete="UploadComplete" OnUploadedComplete="BrowserHidden_UploadedComplete"/>
<button class="ActionButton" id="btnSave" runat="server">Save & Exit</button>
<button class="ActionButton" id="btnClose" runat="serverCancel</button>
<asp:UpdatePanel id="gvupd" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="Label1" />
<asp:GridView id="GridView1" Runat="server" AutoGenerateColumns="False"
AllowPaging="false" EnableViewState="true" datakeynames="Seq">
<Columns>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate><asp:TextBox ID="comments" Enabled="true" MaxLength="249" TextMode="MultiLine" Text='<%# Eval("Comments") %>'/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate><asp:HyperLink id="PictHyper" runat="server" Target="_blank" ImageUrl='<%# String.Format("RCMT0033.aspx?report={0}&seq={1}", Eval("ReportNumber"), Eval("Seq"))%>' NavigateUrl='<%# String.Format("RCMT0034.aspx?report={0}&seq={1}", Eval("ReportNumber"), Eval("Seq"))%>' /></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate><asp:CheckBox runat="server" ID="DeleteCB" /></ItemTemplate>
</asp:TemplateField></Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
THE CODE BEHIND
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoaD
If Not IsPostBack Then
LoadData()
DataBind()
Else
With ViewState
_intReportNumber = CInt(.Item("Report"))
_strVendorNumber = CStr(.Item("VendorNumber"))
_strStatus = CStr(.Item("Status"))
End With
End If
End Sub
Public Sub LoadData()
//GET DATA INTO DATATABLE DT
GridView1.DataSource = dt
GridView1.DataBind()
Catch err As Exception
Throw err
End Try
End Sub
Protected Sub UploadData()
If BrowserHidden.PostedFile IsNot Nothing AndAlso BrowserHidden.PostedFile.FileName <> "" Then
Try
//UPLOAD STUFF
GridView1.DataBind()
Catch ex As Exception
End Try
End If
End Sub
Protected Sub btnClose_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.ServerClick
canceladd()
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "onclick", "window.open('','_self',''); window.close();", True)
End Sub
Protected Sub BrowserHidden_UploadedComplete(ByVal sender As System.Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs)
UploadData()
End Sub
Protected Sub gvupd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gvupd.Load
Label1.Text = DateTime.Now.ToString()
End Sub
Protected Sub btnSave_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.ServerClick
FinalizeAdd()
Page.ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "window.open('','_self',''); window.close();", True)
End Sub
For your #2 issue, I don't think you can reload/refresh the modal window with either client side or server side script. To archive the same or similar result, you can have the upload control to close the modal window and return a value to indicate reopening is needed. then in the parent window, you can use a loop to open it as needed. if user clicks on close button on modal window or the X button on top right, the modal will not be reopened because it does not sent the "reopen" value back to parent.
ParentPage.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ParentPage.aspx.cs" Inherits="WebApplication1.ParentPage" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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">
function popModal(){
var val = window.showModalDialog('ModalChild.aspx', '', '');
while (val == "reopen") {
val = window.showModalDialog('ModalChild.aspx', '', '');
}
}
</script>
</head>
<body>
<input type='button' value='Pop Modal' onclick='popModal();' />
</body>
</html>
ModalChild.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function closeAndReOpen(){
window.returlValue = "reopen";
window.close();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnClientUploadComplete="closeAndReOpen();"
OnUploadedComplete="AsyncFileUpload1_UploadedComplete" />
<input type='button' value='Close' onclick='window.close();' />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img runat="server" id="img" /></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AsyncFileUpload1" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
ModalChild.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
public partial class ModalChild: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGrid();
}
}
protected void LoadGrid()
{
var files = new DirectoryInfo(Server.MapPath("Data")).GetFiles("*.png");
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var fi = e.Row.DataItem as FileInfo;
var img = e.Row.FindControl("img") as HtmlImage;
img.Src = #"Data\" + fi.Name;
}
}
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.PostedFile != null)
{
var savePath = Server.MapPath(#"Data\" + Guid.NewGuid().ToString() + ".png");
AsyncFileUpload1.SaveAs(savePath);
}
}
}
}

Accessing Controls Inside ASP.NET View Controls (Event Handling)

If I have the following ListView, how can I attach a SelectedIndexChanged event listener to the DropDownList so I can perform a command on the respective object? Imagine I have a list of new users and I want to add them to a usergroup by selecting the group from the DropDownList.
<asp:ListView ID="NewUsers" runat="server" DataSourceID="NewUsersSDS" DataKeyNames="ID">
<LayoutTemplate>
<asp:Table ID="groupPlaceholder" runat="server"><asp:TableRow></asp:TableRow></asp:Table>
</LayoutTemplate>
<GroupTemplate>
<asp:TableCell ID="itemPlaceholder" runat="server"></asp:TableCell>
</GroupTemplate>
<ItemTemplate>
<asp:Table ID="NewUsersTable" runat="server" Width="32%" CssClass="inlineTable">
<asp:TableRow>
<asp:TableCell Width="100px"><%# Eval("FullName").ToString.Trim()%></asp:TableCell>
<asp:TableCell>
<asp:HiddenField ID="RowIndex" runat="server" Value="<%# Container.DisplayIndex %>" />
<asp:DropDownList ID="UserGroupSelect" runat="server" DataSourceID="UserGroupSelectSDS" DataValueField="ID" DataTextField="UserGroup"
OnSelectedIndexChanged="UserGroupSelect_SelectedIndexChanged" AutoPostBack="True">
</asp:DropDownList>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ItemTemplate>
</asp:ListView>
I've been having issues accessing controls inside of __View controls. I read in a few places that you could access them by NewUsers.FindControl([ControlID as String]) but this doesn't seem to be working for me. I guess this is what's called a dynamic control? Not really sure, feeling a bit lost.
As always, your help is greatly appreciated. ;)
Additional Info / Code
'Now working code, thanks to James :)
Protected Sub ItemBind(ByVal sender As Object, ByVal e As ListViewItemEventArgs) Handles NewUsers.ItemDataBound
Dim lv As ListView = DirectCast(sender, ListView)
If e.Item.ItemType = ListViewItemType.DataItem Then
lv.DataKeys(e.Item.DataItemIndex).Value.ToString() 'get the datakey
End If
End Sub
Protected Sub UserGroupSelect_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim RowIndex As Integer = CInt(DirectCast(DirectCast(sender, DropDownList).Parent.FindControl("RowIndex"), HiddenField).Value)
Dim pk As Integer = CInt(NewUsers.DataKeys(RowIndex)("ID"))
Try
MessageBox("Update key " + pk.ToString, "Update Key") 'Custom js "alert" box function
Catch ex As Exception
MessageBox("Something went wrong, is the update key empty?")
End Try
End Sub
To access controls in a ListView (or any databound control), you need to use FindControl on the item/row:
ListViewItem item = ListView1.Items[0];
if (item != null)
{
DropDownList ddl = item.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
string value = ddl.SelectedValue;
}
}
As for attaching a SelectedIndexChanged event, you can do it like this:
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Container.DisplayIndex %>' />
</ItemTemplate>
Code-behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);
ListViewItem item = ListView1.Items[rowIndex];
if (item != null)
{
//your logic here
}
}
To retrieve a datakey:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
int rowIndex = Convert.ToInt32(((HiddenField)((DropDownList)sender).Parent.FindControl("HiddenField1")).Value);
int pk = (int)ListView1.DataKeys[rowIndex]["PrimaryKey"];
}

Gridview template radiobuttonlist SelectedInxedChanged, Getting the row the list was in when it fired

I have a Gridview in which one of the template fields has a radiobuttonlist and a dropdownlist. How can I access the row that the radiobuttonlist is in on the SelectedIndexChanged event, so I don't end up updating all of the dropdownlist inside the that template field of the gridview. I don't have any code currently but any help would be greatly appreciated
<asp:TemplateField HeaderText="Column with ListControls" >
<ItemTemplate>
<asp:DropDownList ID="DropdownList1" OnSelectedIndexChanged="SomethingChanged" AutoPostBack="true" runat="server" >
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
</asp:DropDownList>
<asp:RadioButtonList ID="RadioButtonList1" OnSelectedIndexChanged="SomethingChanged" AutoPostBack="true" runat="server">
<asp:ListItem Text="1"></asp:ListItem>
<asp:ListItem Text="2"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
Codebehind VB.NET:
Protected Sub SomethingChanged(ByVal sender As Object, ByVal e As EventArgs)
'in this example this handler is used for both, Dropdownlist and RadiobuttonList'
Dim listControl = DirectCast(sender, ListControl)
Dim row = DirectCast(listControl.NamingContainer, GridViewRow)
Dim item = listControl.SelectedItem
'with FindControl on the row you could also find controls in other columns...'
End Sub
C#:
protected void SomethingChanged(object sender, EventArgs e)
{
//in this example this handler is used for both, Dropdownlist and RadiobuttonList
var listControl = (ListControl)sender;
var row = (GridViewRow)listControl.NamingContainer;
var item = listControl.SelectedItem;
//with FindControl on the row you could also find controls in other columns...
}

Asp.Net and Shadowbox

Trying to pop up an IFrame Shadowbox with Jquery from an asp:gridview datarow. I can't get the proper quotes into the string:
<asp:ImageButton ID="btnEdit" runat="server"
OnClientClick='<%# "javascript:popAccount(\'"+
Eval("id", "Popup.aspx?id={0}")+"\');" %>' />
Parser Error Message: The server tag is not well formed.
Without the escaped single quotes (cannot work, but parses properly):
<asp:ImageButton ID="btnEdit" runat="server"
OnClientClick='<%# "javascript:popAccount("+
Eval("id", "Popup.aspx?id={0}")+");" %>' />
Client-side HTML, as expected:
onclick="javascript:popAccount(Popup.aspx?id=3ce3b19c-1899-4e1c-b3ce-55e5c02f1);"
How do I get quotes into the Javascript?
Edit: added solution. This not very generic, since the databound types must be known in order to access the id property. The key (as defined in the GrodView's DataKeyNames parameter) does not seem to be exposed in the event argument. But it works.
protected void editGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
// do not look at header or footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btn = e.Row.FindControl("btnPopup") as ImageButton;
if (btn != null)
{
btn.OnClientClick =
"javascript:popAccount('EditAccountPopup.aspx?"+
Constants.acctidParam+"="+
((tb_account)(e.Row.DataItem)).id.ToString()+"');";
}
}
Pick up the ImageButton in the GridView's rowdatabound event in the codebehind, and add the property from there.
But are you sure you need to use a server control? How about just a plain image? If you're "replacing" the click-behaviour of the ImageButton, it doesn't seem like you need it at all.
Update:
For the code-behind solution, I coded up this little sample (in VB.NET, sorry):
Private Sub gridview1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridview1.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim btnEdit As ImageButton = CType(e.Row.Cells(0).FindControl("btnEdit"), ImageButton)
Dim strID As String = CType(e.Row.DataItem, Guid).ToString
btnEdit.Attributes.Add("onclick", String.Format("javascript:popAccount('Popup.aspx?id={0}');", strID))
End Select
End Sub
However, I'd still recommend you go with a simpler aproach, jQuery is excellent here. No
need for any code in your codebehind:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("img.edit").click(function() {
var sID = this.id.replace('btnEdit_', '');
alert(sID); // Add your popup opening logic here...
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gridview2" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img id="btnEdit_<%#Container.DataItem %>" class="edit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
If you want to keep your code the way it is, why not just do this?
<asp:ImageButton ID="btnEdit" runat="server"
OnClientClick='<%# "javascript:popAccount(&quot"+
Eval("id", "Popup.aspx?id={0}")+"&quot);" %>' />

Resources