My checkbox on the gridview doesn't trigger an event - c#

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();
}
}

Related

How to get selected item from Dropdown in GridView?

I have a GridView. Whenever I'm clicking on the LinkButton after selecting the Dropdown value, I'm getting only the first item of the Dropdown.
I need to show the selected value in TextBox. How can i get the desired value ?
This is my pseudo code:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EnableModelValidation="True"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Count">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" EnableViewState="true" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Button">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Count", typeof(string));
dt.Rows.Add("A", "5");
dt.Rows.Add("B", "8");
dt.Rows.Add("C", "4");
dt.Rows.Add("D", "7");
dt.Rows.Add("E", "9");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
ddl.Items.Clear();
int count = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Count").ToString());
List<string> list = new List<string>();
for (int i = 1; i <= count; i++)
{
list.Add(i.ToString());
}
ddl.DataSource = list;
ddl.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
DropDownList ddl = (DropDownList)GridView1.Rows[grdrow.RowIndex].FindControl("DropDownList1");
TextBox1.Text = ddl.SelectedValue.ToString();
}
Thanks in advance...
I'm going to guess that you should implement INotifyProperty change with the databinding. This way every change will be recorded including those made after first change in the drop down box. see ~ http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Since you are dynamically creating and binding the Dropdownlist, it would not have loaded at the point your click event is executed. For you to use bound properties (the selectedValue property in this case), the control must already be loaded and it's viewstate info parsed and set by the control.
The databinding event that creates the dropdownlist runs after pre-render. See http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx for details on the page lifecycle.
To do what you are asking requires very close attention to the page life cycle. Try moving the code that sets the textbox to the GridView1_RowDataBound method. For this to work though, your control must be rendered with the same properties everytime (that way the event's on it are wired up correctly and the selectedValue property is set correctly).
Another alternative is to handle events on the textbox or dropdownlist itself. You would again have to pay attention to the properties and lifecycle of the control.
ASP.Net Forms uses the SmartUI pattern and IMHO this is the single greatest knock against this pattern.
Ok, try this
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lnkBtn = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnkBtn.NamingContainer;
DropDownList ddl= (DropDownList)row.FindControl("DropDownList1");
TextBox1.Text = ddl.SelectedValue.ToString();
}

Bind to a hyperlinkfield in a gridview

I have a gridview which pulls data from an xml file. One of the columns of the gridview is a hyperlinkfield. I want to bind a URL field contained in my XML file to this column. I think I have the right idea with the code below but cant figure out how to finish it. The URL is the datakey of the gridview by the way.
protected void grdContents_RowCreated(object sender, GridViewRowEventArgs e)
{
((HyperLinkField)grdContents.Columns[1]).NavigateUrl =
}
you can bind hyperlink on gridView_RowDataBound event like this
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
HyperLinkField lnkHyper = (HyperLinkField)e.Row.FindControl("HyperLinkField1");
lnkHyper.NavigateUrl="";
}
}
try this.
or you can also bind url using DataBinder.Eval at the time of binding source to grid like
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server"
NavigateUrl="<%# DataBinder.Eval(Container.DataItem, "url") %>"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
You can use this as well, as you also providing data source to Grid view.

how to find control of dropdownlist inside a datalist

I have a DataList and inside it I have a DropDownList:
<asp:DataList ID="dlconfigureItem" runat="server">
<ItemTemplate>
<asp:DropDownList CssClass="config-select" ID="ddlitem runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:DataList>
How can I get selectedindexchanged event of DropDownList on the server side? I tried this:
public void ddlitem_selectedindexchanged (object sender, EventArgs e)
{
}
but it is not working.
You have defined the server side method:
public void ddlitem_selectedindexchanged (object sender, EventArgs e)
{
}
but you have not told client side that there is an event for you, so in html code tell it like:
onselectedindexchanged="ddlitem_selectedindexchanged"
and also set AutoPostBack property to true.
From the SelectedIndexChanged event the easiest is to cast the sender to the DropDownList
var ddl = (DropDownList)sender;
The sender is always the control that is the source of the event.
For the sake of completeness, from ItemDataBound of the DataList:
protected void dlconfigureItem_ItemDataBound(object sender, DataListItemEventArgs e)
{
DropDownList ddlitem = e.Item.FindControl("ddlitem") as DropDownList;
if (ddlitem != null)
{
// ...
}
}
Edit: Have you forgotten to register the event?
<asp:DropDownList CssClass="config-select"
ID="ddlitem"
OnSelectedIndexChanged="ddlitem_selectedindexchanged"
runat="server">
</asp:DropDownList>
Note that you should not bind your DataList to it's DataSource on postbacks, otherwise events are not triggered. So check for the IsPostBack property of the page.
For example in page_load:
if(!IsPostBack)BindDataList();
Register the event and set AutoPostBack="true"
<asp:DropDownList CssClass="config-select"
ID="ddlitem"
AutoPostBack="true"
OnSelectedIndexChanged="ddlitem_selectedindexchanged"
runat="server">
</asp:DropDownList>
event (on selected index change you can get the selected value)
protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
{
var ddlList = (DropDownList)sender;
string selectedValue = ((DropDownList)ddlList.NamingContainer.FindControl("ddlitem")).SelectedValue;
}
Not sure if you can't get the selected item on the server or you can't find the way to handle the event. In case your problem is with the event handling, try this
<asp:DataList ID="dlconfigureItem" runat="server">
<ItemTemplate>
<asp:DropDownList CssClass="config-select" ID="ddlitem"
OnSelectedIndexChanged="ddlitem_selectedindexchanged"
AutoPostBack="true" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:DataList>

The FormView fired event ModeChanging which wasn't handled.

Ok, so I'm struggling with using asp:formview.
I've got the formview up and running and I've added the 'Edit' button.
<asp:FormView runat="server" id="fwHotelDetails" DataKeyNames="id" OnDataBound="fwHotelDetails_DataBound" OnModeChanging="fwHotelDetails_ModeChanging" >
<ItemTemplate>
// (..) some code here which outputs some data
<asp:Repeater runat="server" id="repScore">
<ItemTemplate>
<span class="item"> Some output here</span>
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:Repeater>
<EditItemTemplate>
Test test, anything??
</EditItemTemplate>
</ItemTemplate>
</asp:FormView>
I've tried thefollowing solutions in the code behind - none of them works:
protected void fwHotelDetails_ItemCommand(object sender, FormViewModeEventArgs e)
{
if (e.CommandName.Equals("Edit"))
{
fwHotelDetails.ChangeMode(e.NewMode);
}
}
and this:
protected void fwHotelDetails_ModeChanging(object sender, System.Web.UI.WebControls.DetailsViewModeEventArgs e)
{
fwHotelDetails.ChangeMode((FormViewMode)e.NewMode);
}
Clicking the Edit button only gives me the following error message:
The FormView 'fwHotelDetails' fired event ModeChanging which wasn't handled
What more needs to be done?
This page is a great reference for FormView controller: http://authors.aspalliance.com/aspxtreme/sys/web/ui/webcontrols/FormViewClass.aspx
Update: I've updated code to refelct Phaedrus suggestion.
Current status is that even after clicking Edit button, the content from ItemTemplate is loaded.
You have to specify which method handles the ModeChanging event. This event is raised when a FormView control attempts to switch between edit, insert, and read-only mode, but before the mode actually changes.
<asp:FormView OnModeChanging="fwHotelDetails_ModeChanging" />
The second parameter of your method signature is 'DetailsViewModeEventArgs' it should be 'FormViewModeEventArgs'.
void fwHotelDetails_ModeChanging(Object sender, FormViewModeEventArgs e)
{
}
Just Simply write code in formview's Item_Command
protected void formview_ItemCommand(object sender, FormViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
formview.DefaultMode = FormViewMode.Edit;
formview.DataBind();
}
if (e.CommandName == "Cancel")
{
formview.DefaultMode = FormViewMode.ReadOnly;
formview.DataBind();
}
}

Access linkbutton from datalist on pageload with c# asp.net

I have this linkbutton within a datalist and I'm trying to get access to the datalist on the pageload so i can set the linkbutton to be enabled or not based on the user's role.
<asp:DataList id="dlRecommendations" runat="server" DataKeyField="Key" Width="900">
<ItemTemplate>
<asp:LinkButton id="lnkEdit" Text="Edit" Runat="server" CommandName="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
Within the page load I want to be able to access the linkbutton to enable or disable it based on the user's role.
private void Page_Load(object sender, System.EventArgs e) {
//perhaps something like this:
lnkEdit.Enabled = false;
....
}
I think you will be populating the datalist the first time page is loaded. So just wireup ItemDataBound, find link and disable it.
void dlRecommendations_ItemDataBound(object sender, DataListItemEventArgs e)
{
var link = e.Item.FindControl("lnkEdit") as LinkButton;
if (link != null)
{
link.Enabled = UserHasRight;//if user has right then enabled else disabled
}
}
DataList is a databound control - it builds rows only when data is supplied.
To access link inside row use ItemDataBound event and access e.Item.FindControl("linkId");

Categories

Resources