How to get the bound item from within an ASP.NET repeater - c#

I have to set a LinkButton's OnClientClick attribute but I don't know what this value is until the LinkButton is bound to. I'm trying to set the value when the repeater binds, but I can't workout how to get the 'boundItem/dataContext' value...
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton Text="HelloWorld" ID="Hyper1" runat="server" OnDataBinding="Repeater1_DataBinding" >
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<TestObject>();
list.Add(new TestObject() {TestValue = "testing1"});
list.Add(new TestObject() { TestValue = "testing2" });
list.Add(new TestObject() { TestValue = "testing3" });
this.Repeater1.DataSource = list;
this.Repeater1.DataBind();
}
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
//link.DataItem ???
}
Is there anyway to find out what the current rows bound item is?

Maybe you need to use ItemDataBound event. It provides RepeaterItemEventArgs argument which has DataItem available
this.Repeater1.ItemDataBound += Repeater1_ItemDataBound;
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
var dataItem = e.Item.DataItem;
}

I assume you are trying to get the value for the row that is currently being databound?
You can change your function to:
public void Repeater1_DataBinding(object sender, EventArgs e)
{
var link = sender as HyperLink;
string valueYouWant = Eval("TestValue").ToString();
// You could then assign the HyperLink control to whatever you need
link.Target = string.Format("yourpage.aspx?id={0}", valueYouWant);
}
valueYouWant now has the value of the field TestValue for the current row that is being databound. Using the DataBinding event is the best way to do this compared to the ItemDataBound because you don't have to search for a control and localize the code specifically to a control instead of a whole template.

The MSDN library had this as a sample event handler:
public void BindData(object sender, EventArgs e)
{
Literal l = (Literal) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView) container.DataItem)[column].ToString();
}
(see http://msdn.microsoft.com/en-us/library/system.web.ui.control.databinding.aspx)
As you can see it is a simple demonstration of how to access the data item and get data from it. Adapting this to your scenario is an exercise left to the reader. :)

Related

How Do I Bind Dropdown To Value Present In Database

I am using datalist control an asp.net using C# and sqlserver 2008.I have a dropdown in datalist and need to display it's current value from database on page load.
I have tried this so far,
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
DropDownList ddlshowit = (DropDownList)e.Item.FindControl("DropDownList4");
ddlshowit.DataSource = ds;
ddlshowit.DataTextField = "showit";
ddlshowit.DataValueField = "showit"; //showit is my column name
ddlshowit.DataBind();
}
}
I also tried adding the following declaration in markup: SelectedValue='<%#Eval("showit")%>' but it also didn't work. Please Help
You can find your dropdownlist from your datalist in this way,
Protected void Page_load(object sender,Eventargs e)
{
foreach(DataList dl in DataList1.Items)
{
DropDownList ddlshowit = (DropDownList)dl.FindControl("DropDownList4");
}
}
Let me know the output.

Null Value in Label object

I have created on GridView with Label. I have written store procedure to get StatusCode
SELECT StatusCode
From TableName
This line in GridView
< asp:Label ID="lblStatusCode" runat="server" Visible="false"
Text='<%#DataBinder.Eval(Container.DataItem, "StatusCode")%>' />
These lines in .cs file
Label lblStatusCode = (Label)row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
but in lblStatusCode.Text it is showing NULL even though there is value in Table.
When I execute stored procedure independently it is giving values.
// bind function
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindJVJobValidationDetails();
}
}
protected void BindJVJobValidationDetails()
{
JVSummary objJV = new JVSummary();
DataSet dataJobValidation = new DataSet();
if (SessionVariables.PERID != null)
{
dataJobValidation = objJV.GetjvTransaction(SessionVariables.PERID);
gvEmployee.DataSource = dataJobValidation;
gvEmployee.DataBind();
}
}
What might be the problem...?
The text is applied to the control on the page AFTER the code behind runs. Can't you set the text in the code behind?
Edit: You are setting the value of the label on the page i.e aspx / ascx using Container.DataItem but this value is set after the code behind has run. Basically, when the code behind looks at the control it's text property hasn't been set yet. Instead, add a DataRowBinding event to your GridView and set the lblStatusCode.Text in the event in the code behind.
Please try this code on gridview's event
OnRowDataBound="GridView_RowDataBound"
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.DataItem) != null)
{
Label lblStatusCode = (Label)e.row.FindControl("lblStatusCode");
objJV.Status = Convert.ToInt32(lblStatusCode.Text);
}
}
}

Populate second listbox based on the selected value from first listbox

I have 2 list boxes.
<asp:ListBox ID="ListBox_Region" runat="server"
DataTextField="arregion" DataValueField="arregion" AutoPostBack="True"
Height="96px"
Width="147px" DataSourceid="sqldatasource1"></asp:ListBox>
<asp:ListBox ID="ListBox_Area" runat="server"
DataTextField="ardescript" DataValueField="ardescript"
AutoPostBack="True"
OnSelectedIndexChanged="ListBox_Area_SelectedIndexChanged"
Height="96px"
Width="147px" >
So, when I select a value from ListBox_Region , the corresponding values get updated in ListBox_Area in this way:
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}
The event for ListBoxRegion_SelectedIndexChaged is written in page Load.
However, the problem is on initial page load, where the first value of ListBox_Region should be Selected by default. The second listbox should be updated to corresponding values but this should happen before selected index changed gets fired. So, can u please let me know how to do this?
Move the logic on ListBox_Region_SelectedIndexChanged to a separated method and call it from page_load when postback is false.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind ListBox_Region and set the first value as selected
...
//
BindAreaList();
}
}
protected void ListBox_Region_SelectedIndexChanged(object sender, EventArgs e)
{
BindAreaList();
}
protected void BindAreaList()
{
this.ListBox_Area.Items.Clear();
string selectedRegion = ListBox_Region.SelectedValue;
var query = (from s in DBContext.areas
where s.arregion == selectedRegion
select s);
ListBox_Area.DataSource = query;
ListBox_Area.DataBind();
}

ASP.Net dropdownlist not returning index on selectedindexchanged event

I have a dropdownlist control with a selectedindexchanged event that fires correctly. However, when you select an item from the list the index value that is returned to the selectedindexchanged event does not change; the list box pops back tot he first item in the list. Any help would be appreciated. ~susan~
ASP DROP DOWN LIST CONTROL:
<asp:DropDownList ID="CuisineList" runat="server" Width="100"
AutoPostBack = "true" onselectedindexchanged="CuisineList_SelectedIndexChanged" >
</asp:DropDownList>
DATA BOUND TO CONTROL IN PAGELOAD EVENT:
protected void Page_Load(object sender, EventArgs e)
{
//Load drop down lists for restaurant selection
BLgetMasterData obj = new BLgetMasterData();
var cusineList = obj.getCuisines();
CuisineList.DataSource = cusineList;
CuisineList.DataBind();
CuisineList.Items.Insert(0, "Any");
SELECTEDINDEXCHANGEDEVENT:
protected void CuisineList_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
string def = this.CuisineList.SelectedItem.Value;
//aLWAYS returns index '0'
}
}
You need to put your Dropdownlist binding code under !IsPostBack() in the page_load event. like...
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack)
{
BLgetMasterData obj = new BLgetMasterData();
var cusineList = obj.getCuisines();
CuisineList.DataSource = cusineList;
CuisineList.DataBind();
CuisineList.Items.Insert(0, "Any");
}
}
Reason: Whenever your SelectedIndex Change Event fires, the Page_load event is called before the SelectedIndex Change event and your dropdown data rebinded, that's why your currect selection was lost.

How do I retrieve the ListItem value dynamically

I have the following code:
<asp:BulletedList ID="filingList" runat="server" DisplayMode="LinkButton"
onclick="filingList_Click">
</asp:BulletedList>
<asp:Literal ID="filingLiteral" runat="server"></asp:Literal>
and in the backend I fill the bulleted list with ListItems (where AlternateFileUrl is a url string that points to text formatted in html):
foreach (ShortFiling file in filingArray)
{
filingList.Items.Add(new ListItem(file.Type.ToString() + " "
+ file.Date.ToString(), file.AlternateHtmlFileUrl));
}
How do I access the text of the value of the item that's clicked on in the filingList then set it to the asp:Literal control? Here is the empty event handler that I defined and assume that I need to put the code in to set the asp:literal to the value of the specified ListItem.
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
//put code here to set the asp:Literal text to
//the value of the item that is clicked on
}
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
filingLiteral.Text = value;
}
UPDATE 2
Ok you want the text from that URL, keep your markup as it was and change the code behind to this:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
var value = filingList.Items[e.Index].Value;
using(var client = new WebClient())
{
string downloadString = client.DownloadString(value);
filingLiteral.Text = downloadString;
}
}
You will need to add the System.Net namespace.
If I have understood your question correctly, you would just handle the click event of the BulletedList control, like:
protected void filingList_Click(object sender, BulletedListEventArgs e)
{
BulletedList bull = (BulletedList)sender;
ListItem li = bull.Items(e.Index);
filingLiteral.Text = li.Value;
}

Categories