dropdownlist in gridview row data bound is not executing properly - asp.net

I have a dropdownlist in my gridview. The datas in dropdownlist are "Y" and "N".These two letters. If I select Y then the cell value 6 will be need to become zero. But its not working. Here is my code.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList DropDownList3=(DropDownList)e.Row.FindControl("DropDownList");
//if (DropDownList3 == null)
//if (DropDownList3.SelectedValue == "Y")
if(DropDownList3.SelectedItem.Text == "Y")
{
e.Row.Cells[6].Text = "0";
}
else
{
e.Row.Cells[6].Text = "1";
}
}
}
This is my dropdowlist template field
<asp:TemplateField HeaderText="Alt">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" >
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>

First, You have to set AutoPostBack="true" for DropDownList3, and You have to create EventHandler for ddl, but in RowCreated not in RowDataBound.
There is example (it's vb.net) :
aspx:
<asp:TemplateField HeaderText="Alt">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server" AutoPostBack="true">
<asp:ListItem>Y</asp:ListItem>
<asp:ListItem>N</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
and then, code behind :
Private Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid1.RowCreated
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = CType(e.Row.FindControl("DropDownList3"), DropDownList)
AddHandler ddl.SelectedIndexChanged, AddressOf ddlChange
End If
End Sub
Private Sub ddlChange(ByVal sender As Object, ByVal e As EventArgs)
Dim ddl As DropDownList = DirectCast(sender, DropDownList)
Dim row As GridViewRow = ddl.NamingContainer
If ddl.SelectedItem.Text = "Y" Then
row.Cells(6).Text = "0"
Else
' do what You want
End If
End Sub
It's very important You don't bind Your GridView after every PostBack, and, of course, EnableViewState must be set to True.
Since I'm working in vb.net, I'll try to convert this code into c#.
Update :
There is c# code (I used online converter) :
private void GridView1_RowCreated(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
if ((e.Row.RowType == DataControlRowType.DataRow)) {
DropDownList ddl = ((DropDownList)(e.Row.FindControl("DropDownList3")));
ddl.SelectedIndexChanged += new System.EventHandler(this.ddlChange);
}
}
private void ddlChange(object sender, EventArgs e) {
DropDownList ddl = ((DropDownList)(sender));
GridViewRow row = ddl.NamingContainer;
if ((ddl.SelectedItem.Text == "Y")) {
row.Cells[6].Text = "0";
} else {
// do what You want
}
}

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

Add a Grand Total footer to GridView table VS 2010

I am trying to create a Grand Total of all values in a GridView table which will be displayed in the footer, I have started by creating the placeholder but not sure how to go about creating the grand total
<FooterTemplate>
<asp:Label ID="lblGrandTotal" runat="server" Text=""></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
Hi in your gridview do this
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblAmount" runat="server"
Text='<%# Eval("Amount","0:N2}").ToString %>'>
</asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
Now declare like public
Private grdTotal As Decimal = 0
After in the event RowDataBound from your gridview
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowTotal As Decimal =
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
grdTotal = grdTotal + rowTotal
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl("lblTotal"), Label)
lbl.Text = grdTotal.ToString("N2")
End If
If you are adding up just a single column, this should work..
Code-Behind C#
decimal totalA = 0;
protected void gvAlexandria_RowDataBound(object sender, GridViewRowEventArgs e)
{
string totalAmtFinanced = ((Label)gvVehicleTEMP.FooterRow.FindControl("lblTotalAmtFinanced")).Text;
if (e.Row.RowType == DataControlRowType.DataRow)
{
totalA += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "AmtFinanced"));
}
if (e.Row.RowType == DataControlRowType.Footer)
{
//Label lblTotal = (Label)e.Row.FindControl("lblTotal");
if (totalAmtFinanced != null)
{
totalAmtFinanced = String.Format("{0:c}", totalA);
}
}
}
The column in my gridview that I am adding up is called AmtFinanced. This is how I total up a single column. If you have any problems, let me know!

Linkbutton click in a asp:GridView cell does not trigger OnRowCommand event

UI Feature: I have a GridView with few columns. Most important column is PcCode, which shows a string value for each row.
Expected: When I click on one of the cell from a row of that PcCode column another GridView should be displayed. However, when I am trying to use a asp:LinkButton for a cell, things just don't work. RowCommand does not get triggered when I click on a asp:LinkButton in the GridView cell. Where am I doing things wrong? Which way the expected functionality can be achieved? Thanks in advance for helping out a newbie.
In the following code I was trying to get a RowIndex and pass it through the CommandArgument and use a CommandName.
.aspx code
<asp:GridView ID="_UIProfitcenterTotalGridView" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="22" ShowFooter="True" AutoGenerateColumns="False"
DataKeyNames="ProfitcenterCode" EnableViewState="False"
OnRowDataBound="_UIProfitcenterTotalGridView_RowDataBound"
OnPageIndexChanging="_UIProfitcenterTotalGridView_PageIndexChanging"
OnRowCommand="_UIProfitcenterTotalGridView_OnRowCommand">
<Columns>
<asp:TemplateField HeaderText="PcCode" InsertVisible="False"
ShowHeader="False" SortExpression="ProfitcenterCode" FooterText="Total" FooterStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:LinkButton ID="_UIPCCodeLinkButton" runat="server" Text='<%# Eval("ProfitcenterCode") %>'
CommandName="Select"
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
...
code behind for aspx.cs
protected void _UIProfitcenterTotalGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = _UIProfitcenterTotalGridView.Rows[index];
string ProfitcenterCode = _UIProfitcenterTotalGridView.DataKeys[_UIProfitcenterTotalGridView.SelectedIndex].Values["ProfitcenterCode"].ToString();
}
}
After the row is selected I need to take the selected row's value as a string and compare with a listitem to show a new GridView.
Tried
Using Link_Button_Click(Object sender, EventArgs e) and the following but failed.
protected void _UIProfitcenterTotalGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{string ProfitcenterCode = ((GridViewRow)(((LinkButton)e.CommandSource).NamingContainer)).Cells[2].Text;
}
}
I tried to use LinkButton_Click() event instead of RowCommand as jason suggested:
protected void LinkButton_Click(Object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
GridViewRow row = (GridViewRow)button.NamingContainer;
if (row != null)
{
string theValue = ((LinkButton)sender).CommandArgument.ToString();
...
...
//code for the extra thing I needed to do after selecting a cell value.
}
}
However I still had the problem, which I figured out. The problem was the LinkButton was not binding to the rows thefore, it could not pass any value on selection. What was missing was the following code:
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton linkButton = new LinkButton();
linkButton.Text = e.Row.Cells[0].Text; //value of the first column from the grid
linkButton.Enabled = true;
linkButton.Click += new EventHandler(LinkButton_Click); //triggering the LinkButton event here.
e.Row.Cells[0].Controls.Add(linkButton);
}
You can use the sender object ( the link button that calls the event) and get the parent row from the gridview. Example:
Protected Sub linkButton_click(ByVal sender As Object, ByVal e As EventArgs)
'First cast the sender to a link button
Dim btn As LinkButton = CType(sender, LinkButton)
'now, if there is a command arguement, you can get that like this
Dim id As String = btn.CommandArgument
'to get the gridviewrow that the button is on:
Dim row As GridViewRow = CType(btn.NamingContainer, GridViewRow)
End Sub
It was hard to follow exactly what you were looking for, so if i missed something let me know and I will add it.
protected void linkButton_click(object sender, EventArgs e)
{
//First cast the sender to a link button
LinkButton btn = (LinkButton)sender;
//now, if there is a command arguement, you can get that like this
string id = btn.CommandArgument;
//to get the gridviewrow that the button is on:
GridViewRow row = (GridViewRow)btn.NamingContainer;
}
And change your linkbutton to:
<asp:LinkButton OnClick="linkButton_click" ID="_UIPCCodeLinkButton"
runat="server" Text='<%# Eval("ProfitcenterCode") %>'
CommandName="Select"
CommandArgument='<%# ((GridViewRow) Container).RowIndex %>'>

GridView RowCommand Event and Saving Text

I have a GridView set up:
<asp:GridView id="GridView1" Runat="server" AutoGenerateColumns="False" OnRowCommand = "GridView1_RowCommand" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate><asp:Button runat="server" ID="Delete" ImageUrl="~/images/Close.gif" CommandName="DeleteRow" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate><textarea class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
The RowCommand in code-behind is setup like:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "DeleteRow") Then
//do stuff here
The GridView is data bound on Page Load as follows:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Session("CalledModule") = "RCMT0021"
Else
With ViewState
_intRepor = CInt(.Item("Report"))
End With
End If
DataBind() //Gridview Load
End Sub
My questions:
The row command event is never fired. The page just goes into the ELSE (of Not is Postback) in Page_Load
How can I keep track of what all is typed in the "Comments" column of each row (a TEXTAREA), and save the data to the database when a SAVE CHANGES (form) button is clicked?
Thanks!
UPDATE:
The Grid-View's Databinding is as follows:
Public Sub DataBind()
Dim clsDatabase As New clsDatabase
Dim cmd As New OleDbCommand()
Try
cmd.CommandText = "SELECT A, B FROM WHERE C = ? ORDER BY A"
Dim report As New OleDbParameter("#Report", _intReportNumber)
cmd.Parameters.Add(report)
cmd.Connection = clsDatabase.Open_DB()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
dt.Columns.Add(New DataColumn("Seq", GetType(Int16)))
dt.Columns.Add(New DataColumn("ReportNumber", GetType(String)))
Do While (dReader.Read())
Dim dr As DataRow = dt.NewRow()
_strComments = dReader(0).ToString
dr("Seq") = dReader.GetInt16(1)
dr("PictureURL") = "GetImages.aspx?report=" + _intReportNumber.ToString + "&seq=" + dReader.GetInt16(1).ToString
dr("ReportNumber") = _intReportNumber.ToString
dt.Rows.Add(dr)
Loop
GridView1.DataSource = dt
GridView1.DataBind()
Catch err As Exception
End Try
End Sub
So basically, the GridView has three visible columns - a comments field, a picture field, and a field with a delete button (image) to delete the picture (and comments, if any) from the database. The 4th column is a hidden one, keeping track of the the Image ID of the images. I didn't include the picture and other columns for simplicity sake.
The user can add comments, and when he clicks a 'SAVE CHANGES' button, the corresponding comments should get saved for the picture.
The 'SELECT IMAGE' opens up a ModalDialogBox which enables the user to select the image. When closed, it causes a postback, and rebinds the gridview to display the image the user just selected. Therefore, I need the GridView to rebind on postback, or a way around this.
The delete imagebutton (in gridview) should delete the image and comments from the database.
Thanks again!
try this structure...
aspx page: (note textarea has runat="server")
<body>
<form runat="server">
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
EnableViewState="true" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button runat="server" ID="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate>
<textarea runat="server" class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var items = new List<string>();
for (int i = 0; i < 10; i++)
{
items.Add(i + ";comment" + i.ToString());
}
GridView1.DataSource = items;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
var idx = Convert.ToInt32(e.CommandArgument);
var cmt = GridView1.Rows[idx].FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = DateTime.Now.ToString();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem.ToString().Split(";".ToCharArray());
var del = e.Row.FindControl("Delete") as Button;
del.CommandName = "DeleteRow";
del.CommandArgument = item[0];
var cmt = e.Row.FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = item[1];
}
}

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"];
}

Resources