FormView.FindControl(): object reference error - c#

I have a formview that has several textboxes inside of tr/td's. I'm trying to get the textboxes by using the .FindControl method but it's coming back null. The FormView is always in Edit mode (so I'm always in the EditItemTemplate) and i'm trying to load querystring values into the textboxes coming from the previous page so I do need this to happen on page_load. I do this on Gridviews all the time like this:
txtFirstName = (TextBox)fvGeneralInfo.FindControl("txtFirstName");
or like this:
txtFirstName = (TextBox)fvGeneralInfo.FooterRow.FindControl("txtFirstName");
or like this:
txtFirstName = (TextBox)fvGeneralInfo.Rows.FindControl("txtFirstName");
What gives?
<asp:FormView ID="fvGeneralInfo" runat="server"
DataSourceID="objInstructorDetails"
OnItemCommand="fvGeneralInfo_ItemCommand"
OnItemUpdated="fvGeneralInfo_ItemUpdated"
DefaultMode="Edit"
DataKeyNames="InstructorID" >
<EditItemTemplate>
<table>
<tr>
<td colspan="2" class="Admin-SubHeading" style="padding-left:10px;">General Info:</td>
</tr>
<tr>
<td class="Admin-FieldLabel">ID:</td>
<td><asp:TextBox ID="txtInstructorId" runat="server" CssClass="Admin-Textbox" ReadOnly="true" Text='<%# Bind("InstructorID") %>' /></td>
</tr>
<tr>
<td class="Admin-FieldLabel">First Name:</td>
<td><asp:Textbox ID="txtFirstName" runat="server" CssClass="Admin-Textbox" Text='<%# Bind("FirstName") %>' /></td>
</tr>
</table>
</EditItemTemplate>
</asp:FormView>

abatishchev's answer is right, although I found this variation a bit neater: it avoids having to call DataBind() explicitly.
<asp:FormView ID="fvMember" runat="server" DataSourceID="tblMembers" DefaultMode="Insert" OnDataBound="DataBound">...</asp:FormView>
protected void DataBound(object sender, EventArgs e)
{
if (fvMember.CurrentMode == FormViewMode.Edit)
{
Label lblSubmit = fvMember.FindControl("lblSubmit") as Label;
...
}
}

Call DataBind(); first. Then FindControl()

Related

Highlight ListView row without re-bind or apply style to that row

Typical listview.
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" OnSelectedIndexChanging="ListView1_SelectedIndexChanging"
OnSelectedIndexChanged="ListView1_SelectedIndexChanged">
<ItemTemplate>
<tr style="">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' />
</td>
<td>
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' />
</td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn"
CommandName="Select"/>
</td>
</tr>
</ItemTemplate>
<SelectedItemTemplate>
<tr style="" class="alert-info">
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
</td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
</td>
<td>
<asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' />
</td>
<td>
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' />
</td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn" OnClick="cmdLstSel_Click" />
</td>
</tr>
</SelectedItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">View</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
So we can highlight the row clicked with:
protected void ListView1_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
{
}
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
GPayments.DataSource = MyRst("SELECT * FROM HotelPayments WHERE Hotel_ID = " + hID);
GPayments.DataBind();
}
Now if I leave out the re-bind, then of course the row will highlight, but of course it is the "previous" row that hight lights.
And if I could set the class of the ONE row, then I could dump the selected item template.
You can do this with GREAT ease in a GridView, and I often do this:
Dim gRow As GridViewRow = -- get any row
gRow.CssClass = " alert-info"
however, I would like to do the same with listView. When I do above for GridView, then I don't need or have to bother with a re-bind, and I don't even need a selected template either.
So left is a grid view, and we get this:
However, I want to do this with listview.
(and WITHOUT having to do a re-bind).
Any simple way to highlight a row in ListView WITHOUT a re-bind?
Ok, a bit of googling, and the solution becomes VERY easy.
The goal here is to click on a row - highlight that row.
Of course WAY too much work to have to include a selected row template.
It is a better trade off to add 3 lines of code to do this.
So, say we have this markup:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID"
OnSelectedIndexChanged="ListView1_SelectedIndexChanged" OnSelectedIndexChanging="ListView1_SelectedIndexChanging" >
<ItemTemplate>
<tr id="mytr" runat="server">
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td>
<asp:Button ID="cmdLstSel" runat="server" Text="View" CssClass="btn"
CommandName="Select" OnClick="cmdLstSel_Click"/>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" class="table table-hover" style="">
<tr runat="server" style="">
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">View</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
ok, our code to fill is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadView();
}
}
void LoadView()
{
ListView1.DataSource = MyRst("SELECT TOP 12 * FROM tblHotels ORDER BY HotelName");
ListView1.DataBind();
}
Output:
Ok, so for the row click? Well, we don't have to use the selected index changed, but, for this we will (so CommandName="Select" is what triggers that index changed event).
However, I want a simple button click, and with some code (to display the details part).
So, our button click is this:
protected void cmdLstSel_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
ListViewDataItem gRow = (ListViewDataItem)btn.Parent.Parent.Parent;
int hID = (int)ListView1.DataKeys[gRow.DisplayIndex]["ID"];
GHotelOptions.DataSource = MyRst("SELECT * FROM HotelOptions WHERE Hotel_ID = " + hID);
GHotelOptions.DataBind();
GPayments.DataSource = MyRst("SELECT * FROM HotelPayments WHERE Hotel_ID = " + hID);
GPayments.DataBind();
}
Above will fill the child tables. Note the cool trick to get the row - I don't bother with the listview event model!
Now for the row highlight.
The trick is to add an "id" to the tr row like this:
<ItemTemplate>
<tr id="mytr" runat="server">
So, we can now pick up the tr element.
So on lv index changed, we do this:
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem gRow = (ListViewItem)ListView1.Items[ListView1.SelectedIndex];
if ( (ViewState["MySel"] != null) && ((int)ViewState["MySel"] != gRow.DataItemIndex) )
{
ListViewItem gLast = ListView1.Items[(int)ViewState["MySel"]];
HtmlTableRow hTRL = (HtmlTableRow)gLast.FindControl("mytr");
hTRL.Attributes.Add("class", "");
}
HtmlTableRow hTR = (HtmlTableRow)gRow.FindControl("mytr");
hTR.Attributes.Add("class", "alert-info");
ViewState["MySel"] = gRow.DataItemIndex;
}
So, I did use row state, but that lets me un-highlight + highlight, and I do NOT hve to re-bind the grid.
And I just picked a nice boot strap class - it even "reverses" the text - very nice.
So now we get this:
So this did cost about 4-5 extra lines. But, we trade that for NOT having a selected template in the lv (and that's too much to maintain both the row layout and THEN have to maintains the same for selected template. And worse, you STILL had to re-bind for the highlighted row click to show. This way, we don't.
I also used a "helper" routine to get a datatable, and that was this:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
return rstData;
}
At the end of the day, we can now highlight the row, do so with a click, and we could even move the selected index changed code to our button code and not even use the lv index and built in events.

Have Checkbox inside repeater send data from Textbox inside repeater to another Textbox outside of repeater

I have a repeater that populates a list of 3 columns and has a Checkbox next to each row. I am trying to create a scenario in which a person checks a row, the page locates the "Portion Name" text box inside of the repeaters row that corresponds with the row where the checkbox has been clicked, and once that checkbox is selected, it sends the Portion Name to another textbox outside the repeater called "testTextBox.Text". I have my code below, and am sure I am missing something as I have not done a "OnCheckChanged" event before, I am only familiar with onTextChanged events.
Below is the code:
<asp:Repeater ID="rptAccount" runat="server" OnItemCommand="rptAccount_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<th>Account
</th>
<th>Portion ID
</th>
<th>Portion Name
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="Account" runat="server" Width ="50px" Text='<%#Eval("Account") %>' ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="PortionID" runat="server" Width ="90px" Text='<%#Eval("Portion ID") %>' ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="PortionName" runat="server" Width ="340px" Text='<%#Eval("Portion Name") %>'></asp:TextBox>
</td>
<td>
<asp:CheckBox ID="Name" runat="server" OnCheckedChanged = "TbName_CheckedChanged" Checked='<%# Eval("Name").ToString() == "True" %>' ></asp:CheckBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
cs code:
protected void TbName_CheckedChanged(object sender, EventArgs e)
{
var PortionName = (sender as TextBox).Parent;
var rptAccount = (sender as TextBox).Parent;
var checkedd = rptAccount.FindControl("Name") as CheckBox;
var PortionNamee = rptAccount.FindControl("PortionName") as TextBox;
if (checkedd.Checked)
{
testTextBox.Text = PortionNamee.Text;
}
}
Thank you for any help you can offer.
The repeater ends up having a ton of controls with the name Name. Remember the template is repeated many times. you need to find the index of the current item. An easier way its to attach an attribute to the checkbox to hold the text value, that way you can extract it straight from the sender without having to worry about parent and index. Try this:
<asp:Repeater ID="rptAccount" runat="server" OnItemCommand="rptAccount_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<th>Account
</th>
<th>Portion ID
</th>
<th>Portion Name
</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="Account" runat="server" Width ="50px" Text='<%#Eval("Account") %>' ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="PortionID" runat="server" Width ="90px" Text='<%#Eval("Portion ID") %>' ></asp:TextBox>
</td>
<td>
<asp:TextBox ID="PortionName" runat="server" Width ="340px" Text='<%#Eval("Portion Name") %>'></asp:TextBox>
</td>
<td>
<asp:CheckBox ID="Name" runat="server" OnCheckedChanged = "TbName_CheckedChanged" CommandName='<%#Eval("Portion Name") %>' Checked='<%# Eval("Name").ToString() == "True" %>' ></asp:CheckBox>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
cs code:
protected void TbName_CheckedChanged(object sender, EventArgs e)
{
var checkedd = sender as Checkbox;
if (checkedd.Checked)
testTextBox.Text = checkedd.Attributes["CommandName"];
}

How to databind to a Gridview where column values should appear in sub rows within a main row?

Please can anyone suggest a way to databind a database table to a gridview but in a specific layout where column values should appear in sub rows within a main row, like wise all rows from the database table should list down inside that Gridview.I know the normal way of databinding to a gridview Where it display row data(From Database Table) as columns, but what I want is like below
Gridview is not suitable for this type of format.
If you are okay with repeater, you can do something like this:
And here's a link to MSDN: Repeater Class.
UPDATE: If you want to post each answer selection, you can use option button and group them. You can use questionid as a part of group name and in the code get the question id. Your markup may look like below:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<th colspan="2"></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# DataBinder.Eval(Container.DataItem, "QuestionId") %> </td>
<td>
<table>
<tr>
<td colspan="4"><%# DataBinder.Eval(Container.DataItem, "Question") %> </td>
</tr>
<tr>
<td>
<asp:RadioButton ID="RadioButton1" runat="server" AutoPostBack="true" Text='<%# DataBinder.Eval(Container.DataItem, "Answer1") %>'
OnCheckedChanged="RadioButton1_CheckedChanged" GroupName='<%# Eval("QuestionId","Grp_{0}") %>' TextAlign="Left" />
</td>
<td><asp:RadioButton ID="RadioButton2" runat="server" AutoPostBack="true" Text='<%# DataBinder.Eval(Container.DataItem, "Answer2") %>'
OnCheckedChanged="RadioButton2_CheckedChanged" GroupName='<%# Eval("QuestionId","Grp_{0}") %>' TextAlign="Left" />
</td>
<td><asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="true" Text='<%# DataBinder.Eval(Container.DataItem, "Answer3") %>'
OnCheckedChanged="RadioButton3_CheckedChanged" GroupName='<%# Eval("QuestionId","Grp_{0}") %>' TextAlign="Left" />
</td>
<td><asp:RadioButton ID="RadioButton4" runat="server" AutoPostBack="true" Text='<%# DataBinder.Eval(Container.DataItem, "Answer4") %>'
OnCheckedChanged="RadioButton4_CheckedChanged" GroupName='<%# Eval("QuestionId","Grp_{0}") %>' TextAlign="Left" />
</td>
</tr>
</table>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And in the code:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
string grpId = ((RadioButton)sender).GroupName;
int questionId = 0;
int.TryParse(grpId.Split('_')[1].ToString(), out questionId);
//Use questionId
}

Can't find fields using FindControl in a FormView

I wonder if anyone can help me with this. I've been searching for answers and get so far but think I'm missing something.
I have a FormView that was created using Dynamic Data. Within that FormView I have 3 fields, ItemCosts, AdditionalCosts and TotalCosts. I would like to be able to put a button on the form that adds the ItemsCosts and AdditionalCosts together and displays it in the TotalCosts textbox. Simple enough... so I thought.
I've discovered I need to use ItemCommand as the FormView uses this command when posting back. This is what I have written:
HTML
<asp:Panel ID="DetailsPanel" runat="server">
<br /><br />
<asp:FormView ID="FormView1" runat="server" DataSourceID="DetailsDataSource" RenderOuterTable="false"
OnPreRender="FormView1_PreRender" OnModeChanging="FormView1_ModeChanging" OnItemUpdated="FormView1_ItemUpdated"
OnItemInserted="FormView1_ItemInserted" OnItemDeleted="FormView1_ItemDeleted" OnItemCommand="FormView1_ItemCommand" OnDataBinding="FormView1_DataBind">
<HeaderTemplate>
<table id="detailsTable" class="DDDetailsTable" cellpadding="6">
</HeaderTemplate>
<ItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" DataField="ItemCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">AdditionalCosts</td>
<td><asp:DynamicControl runat="server" DataField="AdditionalCosts" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" DataField="TotalCosts" /></td>
</tr>
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit" Text="Edit" />
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="Delete" Text="Delete"
OnClientClick='return confirm("Are you sure you want to delete this item?");' />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr class="td">
<td class="DDLightHeader">Order No</td>
<td><asp:DynamicControl ID="OrderNo" runat="server" DataField="OrderNo" Mode="ReadOnly"/></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Item Costs</td>
<td><asp:DynamicControl runat="server" DataField="ItemCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Additional Costs</td>
<td><asp:DynamicControl runat="server" DataField="AdditionalCosts" Mode="Edit" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">Total Costs</td>
<td><asp:DynamicControl runat="server" DataField="TotalCosts" Mode="Edit" /></td>
<td><asp:Button runat="server" ID="btnCalculateTotalCosts" Text="Calculate total costs" CommandName="Calculate" /></td>
</tr>
<tr class="td">
<td class="DDLightHeader">View Items</td>
<td><asp:DynamicControl runat="server" DataField="tblCateringOrdersDetailsItems" Mode="Edit" /></td>
</tr>
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton4" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="LinkButton5" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DynamicEntity ID="DynamicEntity3" runat="server" Mode="Insert" />
<tr class="td">
<td colspan="2">
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="LinkButton7" runat="server" CommandName="Cancel" Text="Cancel" CausesValidation="false" />
</td>
</tr>
</InsertItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:FormView>
<asp:EntityDataSource ID="DetailsDataSource" runat="server" EnableDelete="true" EnableInsert="true" EnableUpdate="true" />
<asp:QueryExtender ID="QueryExtender1" TargetControlID="DetailsDataSource" runat="server">
<asp:ControlFilterExpression ControlID="GridView1" />
</asp:QueryExtender>
</asp:Panel>
I've added a btnCalculateTotalCosts button in the EditTemplate section.
In the code behind I've created an ItemCommand control
protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Calculate")
{
FormViewRow row = FormView1.Row;
decimal itemCosts;
decimal additionalCosts;
TextBox itemsCostTextBox = (TextBox)row.FindControl("ItemCosts");
TextBox additionalCostsTextBox = (TextBox)row.FindControl("AdditionalCosts");
TextBox totalCostsTextBox = (TextBox)row.FindControl("TotalCosts");
Decimal.TryParse(itemsCostTextBox.Text, out itemCosts);
Decimal.TryParse(additionalCostsTextBox.Text, out additionalCosts);
totalCostsTextBox.Text = (itemCosts + additionalCosts).ToString();
}
But I keep getting an 'error Object reference not set to an instance of an object'. I've read that you have to bind the fields to the FormView first so I tried to create the following
protected void FormView1_DataBind(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
TextBox itemsCostTextBox = (TextBox)FormView1.FindControl("ItemCosts");
TextBox additionalCostsTextBox = (TextBox)FormView1.FindControl("AdditionalCosts");
TextBox totalCostsTextBox = (TextBox)FormView1.FindControl("TotalCosts");
}
}
and reference the DataBind in the tag as OnDataBinding="FormView1_DataBind" but this didn't work either and I'm getting the same error.
I really have tried to work this out and realise that the FindControl is not 'seeing' the fields in FormView but I just can't work out how to do this.
Any help would be greatly appreciated
Thank you
FindControl() receives the ID for the control you are looking for. From ASPX code you posted I'm not seeing that you are setting the ID property for DynamicControls you are trying to find using FindControl(). This call to that method:
TextBox itemsCostTextBox = (TextBox)row.FindControl("ItemCosts");
is passing the DataField property value instead of the ID. Add the ID property to all DynamicControls that you want to find.
Also take into account that FindControl() does not perform a recursive search, it only looks for a control with the specified ID between the control's children.
In case it helps anyone else:
protected void FormView1_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Calculate")
{
// ...
//instead of this...
TextBox itemsCostTextBox = (TextBox)row.FindControl("ItemCosts");
//(no need to use row here, just use the reference to the FormView;
//also no need to add an ID to DynamicControl because it creates
//its own ID out of the field name and template control name)
//cast like this...
var itemsCostTextBox = (TextBox)FormView1.FindFieldTemplate("ItemCosts").TemplateControl.FindControl("txtTextBox1");
//txtTextBox1 is the name of the specific web UI control inside of
//the DynamicData *.ascx template that you want access to
}
}

How I get the right Line Index of the ListView

I wrote a ASP.NET Application that get Data from the Active Directory. I use a ListView to display this data. The User input a String (Lastname or a part of this) in a TextBox. Than the ListView list all AD Users with the same string from the TextBox. Every Line get a Button "Anzeigen" to get more Informations about the User. This ListView has six columns and every line show a User. in column number six is the button "Anzeigen". If a User click on this button open a new WebForm "benutzer.aspx" with more Informations abaout this seleced User and get a Session Value "email" from the line.
My Problem:
I don't know how I get the Index of the Line of the ListView that I need for the Session Value.
My Code:
cs file:
protected void Button1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Anzeigen")
{
//This give me everyone the Value -1 back
int selectedLine = myListView.SelectedIndex;
//I need the Line Index for the right Value
Label lb = (Label)myListView.Items[selectedLine].FindControl("Label2");
string email = lb.Text;
Session["email"] = email;
Response.Redirect("Benutzer.aspx");
}
}
ASPX File:
...
<ItemTemplate>
<tr runat="server">
<td align="left" ><asp:Label ID="Label1" Text='<%# Eval("Benutzer") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label2" Text='<%# Eval("eMail") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label3" Text='<%# Eval("Vorname") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label4" Text='<%# Eval("Nachname") %>' runat="server" /></td>
<td align="left"><asp:Label ID="Label5" Text='<%# Eval("Telefon") %>' runat="server" /></td>
<td align="left"><asp:Button ID="Button1" Text="Anzeigen" OnCommand="Button1_Command" CommandName="Anzeigen" CommandArgument="myArgument" runat="server" /></td>
</tr>
</ItemTemplate>
...
I search and I found listview selectedindices but it don't work :( and I dont't can use it in my Application .
tarasov
Use ListView's ItemCommand rather than Button's on command
see http://www.codeproject.com/Articles/24570/Complete-ListView-in-ASP-NET-3-5
for more detail.
One more thing From example you can see that author has extracted the values from e.Item. You can pass the key(email,username or whatever) as CommandArgument and can access that value directly from command argument.
how to pass it
<asp:LinkButton ID="myLink" runat="server" CommandName="Anzeigen" CommandArgument='<%#Eval("KeyColumn")%>'>Anzeigen</asp:LinkButton>
Also use Linkbutton rather than Asp:Button
ASPX:
<td align="left"><asp:Button ID="Button1" Text="Anzeigen" OnCommand="Button1_Command" CommandName="Select" CommandArgument='<%# Container.DataItemIndex %>' runat="server" /></td>
CS:
protected void Button1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);
Label lb = (Label)myListView.Items[index].FindControl("Label2");
string email = lb.Text;
Session["email"] = email;
Response.Redirect("Benutzer.aspx");
}
}

Categories