Datalist_ItemCommand event not firing - c#

I have a datalist that has an item_Command event that is never firing.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
DataList1.DataSource = mySource;
}
protected void DataList1_ItemCommand(object sender, DataListCommandEventArgs e)
{
//dostuff
}
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand"
OnItemCreated="DataList1_ItemCreate">
<ItemTemplate>
<table>
<tr>
<td>
<asp:Button ID="ButtonEditTask" runat="server" Width="60px" Text="Edit" CommandName="edit" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
When I do the postback, my datasource is null since I am not re assigning, therefore my event handler doesnt fire. So in order to fix it being null, i tried overriding init
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
DataList1.DataSource = mySessionSource;
}
Now I know the reason why its not working is because either
1. My Datasource is null BEFORE I added in the Override method and
2. My Controls event handler isn't being created in time since its rebinding every postback.
To fix 1, I added a datasource.
To fix 2 I added a datasource in init.
This didn't seem to fix anything however, and I do not know why. I also tried adding an event_handler in my init and it didn't do anything.

Make sure that you're binding the datasource to DataList1 otherwise the DataList will always be empty and the OnItemCreated event will never fire. You shouldn't need the OnInit override.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataList1.DataSource = mySource;
DataList1.DataBind();
}
}

Related

My checkbox on the gridview doesn't trigger an event

I created my gridview with checkboxes inside of it with this code.
<asp:GridView ID="GridView1" runat="server" Width="366px" autogeneratecolumn="false">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="SelectAllCheckBox" runat="server" AutoPostBack="true" oncheckedchanged="SelectAllCheckBox_OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EachCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I tried check/uncheck it.
enter link description here
protected void SelectAllCheckBox_OnCheckedChanged(object sender, EventArgs e)
{
String test = "test";
test = "newtest";
GridView1.DataSource = null;
GridView1.DataBind();
}
But it doesn't trigger any event.
enter link description here
I'm trying to find where my code is missing and searched so far but still can't.
Thank you for your help!
You must use OnItemCreated or OnItemDataBound and link your checkbox with your delegate
void Item_Created(Object sender, DataGridItemEventArgs e)
{
CheckBox cbx = (CheckBox)e.Item.FindControl("SelectAllCheckBox");
cbx.CheckedChanged += SelectAllCheckBox_OnCheckedChanged;
}
The code looks fine and works for me.
I suspect you might be binding the GridView on every postback.
When you click the CheckBox with the event attached it causes the page to refresh. If you bind the CheckBox on Page_Load (or any method that occurs on every trip to the server) it will bind the grid every time you click the CheckBox. In this case it will never get as far as firing your event.
If so, try checking for a postback before binding your GridView.
For example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = myDataSource;
GridView1.DataBind();
}
}

How to get Text property of TextBox after ItemCommand event

I have a TextBox control inside a panel and this panel is inside DataList ItemTemplate.
After firing the ItemCommand event, everything works fine except that the TextBox.Text property is always an empty string "" although there is some text in it.
I tried several ways but without success. I would really appreciate if someone can assist me with this. Simplified code is shown below.
Thank you!
ASPX page:
<asp:DataList ID="dlDataList" runat="server" onitemcommand="dlDataList_ItemCommand">
<ItemTemplate>
<asp:Panel ID="pnlReply" runat="server" Visible="False">
<asp:TextBox ID="txtTextBox" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkbtnSend" CommandName="Send" runat="server">Send</asp:LinkButton>
</asp:Panel><br />
<asp:LinkButton ID="OpenPanel" CommandName="OpenPanel" runat="server">Open panel</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</asp:Content>
ASPX.CS Page code behind
protected void Page_Load(object sender, EventArgs e)
{
FillDataList();
}
private void FillDataList()
{
List<string> list = new List<string>();
list.Add("First");
list.Add("Second");
list.Add("Third");
dlDataList.DataSource = list;
dlDataList.DataBind();
}
protected void dlDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "OpenPanel")
{
Panel pnlReply = (Panel)e.Item.FindControl("pnlReply");
pnlReply.Visible = true;
}
if (e.CommandName == "Send")
{
TextBox txtTextBox = (TextBox)e.Item.FindControl("txtTextBox");
//I tried this way also..
//TextBox txtTextBox = (TextBox)e.item.FindControl("pnlReady").FindControl("txtTextBox");
Label1.Text = txtTextBox.Text;
}
}
Please use IsPostBack in page load event. Without it your FillDataList(); is executing on every postback and resetting your DataList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDataList();
}
}

LinkButton not working within UpdatePanel

I'm building a table of data for price quotes (think table of Stock quotes) which needs to be refreshed every 5 secs. Each row has some data about one Stock in several columns and the last column in each row has a LinkButton to see more info about that particular stock. Everything works but the LinkButton. The entire table is nested inside an UpdatePanel which I think is causing the problem. I've seen a fair number of posts on this topic but none that have worked for me.
Here is my .aspx code:
<asp:ScriptManager ID="ScriptManager" runat="server" />
<asp:Timer ID="Timer" OnTick="Timer_Tick" runat="server" Interval="5000" />
<div id="itemList">
<asp:UpdatePanel ID="itemPanel" UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server">
<Triggers><asp:AsyncPostBackTrigger ControlID="Timer" /></Triggers>
<ContentTemplate>
<asp:Panel ID="Panel_ItemList" runat="server" width="100%"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
and my .aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
...
if (!Page.IsPostBack)
{
updateItemsTable();
}
}
protected void LinkButton_Click(object sender, CommandEventArgs e)
{
Panel_LoginAlert.Visible = true; // <-- THIS IS NOT FIRING!!
}
protected void Timer_Tick(object sender, EventArgs e)
{
updateItemsTable();
}
protected void updateItemsTable()
{
//... Query my DB
if (rdr.HasRows)
{
Panel_ItemList.Controls.Add(new LiteralControl("<!-- ItemList Panel -->\n"));
while (rdr.Read())
{
LinkButton lb = new LinkButton();
lb.Text = "Item";
lb.ID = "lbItem_" + strDBitemID;
lb.CommandName = strDBitemName;
lb.CommandArgument = strDBitemID;
lb.Command += new CommandEventHandler(LinkButton_Click);
Panel_ItemList.Controls.Add(lb);
}
Panel_ItemList.Controls.Add(new LiteralControl("<!-- END ItemList Panel -->\n"));
}
//...
conn.Close();
}
So the page loads fine and the timer reloads the table fine, but the LinkButtons do not fire the CommandEventHandler. This works fine if I remove the Timer.
Things I've tried:
I tried using Buttons rather than LinkButtons but this didn't help.
I read dozens of posts saying to add an ID to the LinkButton controls, but this didn't help either.
I believe the problem is when your adding the controls. For this to work the server controls need to be added in the Init event, or overriding OnInit(EventArgs).
Instead of explicitly creating the controls you could replace the panel with a repeater. Then bind your results from the database to the reader.
<asp:Repeater ID="TheRepeater" ...>
<ItemTemplate>
<asp:LinkButton onClick="LinkButton_Click" ...bind values to properties here />
</ItemTemplate>
</asp:Repeater>
code behind
TheRepeater.Visible = rdr.HasRows;
TheRepeater.DataSource = rdr;
TheRepeater.DataBind();
That being said, if all you want to do is alter the UI, that could easily be accomplished with jquery.
I believe the problem is in the page life cycle, since you are creating a dynamic control and adding the event after the page_init or page_load, its not getting hooked up correctly to the control, you could try out the following and see if it works:
Add page init:
protected void Page_Init(object sender, EventArgs e)
{
updateItemsTable();
}
and change the timer tick event to:
protected void Timer_Tick(object sender, EventArgs e)
{
itemPanel.Update();
}
and that should do the trick.
Hope this is of help.
Cheers.
You need to add postback trigger as following:
<asp:PostBackTrigger ControlID="SearchBrn"/>

How do I delete an item from a ListView using a custom DataSource?

I have a ListView with an IEnumerable<MyDocument> DataSource pulled from a method.
The code in myDocsList_ItemCommand() definitely runs, because the document is actually deleted. My problem is that the ListView still shows the (now deleted) document until the next page refresh, even though I have code to do myDocsList.Items.Remove(dataItem).
The simplified .ascx is basically:
<asp:ListView id="myDocsList" runat="server"
OnItemDataBound="myDocsList_ItemDataBound"
OnItemDeleting="myDocsList_ItemDeleting"
OnItemCommand="myDocsList_ItemCommand">
<LayoutTemplate>
<table>
<asp:Placeholder id="itemPlaceholder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr><td>
<asp:LinkButton
ID="delete" runat="server"
CommandName="Delete" CommandArgument="X"
OnClientClick="javascript:return confirm('...');">
Delete
</asp:LinkButton>
</td></tr>
</ItemTemplate>
</asp:ListView>
The simplified .ascx.cs is basically:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
IEnumerable<MyDocument> docs = getDocuments();
myDocsList.DataSource = docs;
myDocsList.DataBind();
}
}
/* so we have the ID of the document we're deleting later on */
protected void myDocsList_ItemDataBound(object sender,
ListViewItemEventArgs e)
{
var deleteButton =
(LinkButton) ((Control) e.Item).FindControl("delete");
deleteButton.CommandArgument =
((MyDocument) e.Item.DataItem).id.ToString();
}
/* or we get "raised event ItemDeleting which wasn't handled" */
protected void myDocsList_ItemDeleting(Object sender,
ListViewDeleteEventArgs e)
{
}
/* do something here? */
//protected void myDocsList_ItemDeleted(Object sender,
// ListViewDeletedEventArgs e)
//{
//}
protected void myDocsList_ItemCommand(object sender,
ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int docId = int.Parse(e.CommandArgument.ToString());
deleteDocument(docId);
ListViewDataItem dataItem = (ListViewDataItem) e.Item;
myDocsList.Items.Remove(dataItem);
}
}
I've been reading up on the ASP page lifecycle and a few related questions, but I'm reasonably inexperienced with ASP and a bit lost.
How do I get my ListView items to disappear on the PostBack instead of on the next page refresh?
You have to rebound data to your ListView in ItemCommand event, you can change your coding style as below:
//Create a new method for databind
void BindData()
{
IEnumerable<MyDocument> docs = getDocuments();
myDocsList.DataSource = docs;
myDocsList.DataBind();
}
//Call databind method in your prerender event
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
//Again bind data after delete operation
protected void myDocsList_ItemCommand(object sender,
ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int docId = int.Parse(e.CommandArgument.ToString());
deleteDocument(docId);
BindData();
}
}

Image.ImageUrl not working (C#, asp.net)

I have the next code:
<asp:ListView ID="LV1" runat="server" DataSourceID="LinqDataSource">
<ItemTemplate>
<asp:Image ID="Image1" Width="100px" Height="100px" runat="server" />
//....and so on till the
</asp:ListView>
The code behind:
protected void checkTheImage()
{
foreach (ListViewItem item in LV1.Items)
{
((Image)item.FindControl("Image1")).ImageUrl = "~/noImage.jpg";
}
}
And page load:
protected void Page_Load(object sender, EventArgs e)
{
checkTheImage();
}
The problem is - the noImage.jpg is not display... why ?
not sure if your markup is ok, you should also have a closing ItemTemplate tag somewhere... please update your markup.
just to try out things, does it work if you move the call of checkTheImage(); inside the Page_PreRender?
is there any place where you DataBind the ListView in your page life cycle?
May be you need to rebind the ListView.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LV1.DataBind();
checkTheImage();
}
}

Categories

Resources