Trigger SelectedIndexChanged event ASP.NET - asp.net

I have a DropDownList inside a GridView. I want to make some updates on database inside the SelectedIndexChanged it's not being triggered.
PS: I tried all the solutions I found over internet but always the same problem.
Here is code:
<asp:TemplateField HeaderText="Accepté" ControlStyle-Width="90px">
<ItemTemplate >
<asp:Label ID="lblState" runat="server" Text='<%# Eval("StateCode") %>' Visible = "False" />
<asp:DropDownList ID="ddlState" runat="server" Visible = "False" OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField >
And the code behind
protected void grwConsent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text != " ")
{
DropDownList ddlState = e.Row.FindControl("ddlState") as DropDownList;
if (null != ddlState)
{
ddlState.Visible = true;
string stateValue = (e.Row.FindControl("lblState") as Label).Text;
ConsentHelper.LoadConsentStatesInList(ddlState,"-----",stateValue);
ddlState.Items.RemoveAt(0);
ddlState.Items.FindByText(stateValue).Selected = true;
}
}
}
}
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
//Database Updates
}
Thank you!

Try adding these properties to you DropDownList:
ViewStateMode="Enabled"
EnableViewState="true"
AutoPostBack="true"
<asp:DropDownList ID="ddlState" AutoPostBack="true" EnableViewState="true"
ViewStateMode="Enabled" runat="server" ...

Related

DropDownList inside Grid

I am using ASP.NET, I have a dropdownlist inside of a grid (radGrid).
What I like to happen is that when the dropdownlist appears, I like it to default to
"Please Select" only if the field that it is binding to is blank. Else, I like to to get the value from the DataSource.
I have the following code:
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
For the DataSource here is the code:
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
Here is the code in the code-behind:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list != null)
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
When it does the Binding, if the value is blank, I get an error saying that it could not find the value.
try:
protected void ErogroupDropDown_DataBound(object sender, EventArgs e)
{
DropDownList list = sender as DropDownList;
if (list.Items.Count.equals(0))
{
list.Items.Insert(0, new ListItem("Please Select", ""));
}
}
Use Grid PreRender event for this. May you would need to assign the value to some hidden label and access it inside prerender method and assign it to the dropdown.
<ItemTemplate>
<asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" />
<asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>
</asp:DropDownList>
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"
SelectCommand="Select Value from LookupValues where Category = 'EroGroup'">
</asp:SqlDataSource>
</ItemTemplate>
On code behind:
protected void GridView1_PreRender(object sender, EventArgs e)
{
for(int i=0;i<Gridview1.Rows.Count;i++)
{
Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue');
DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup');
ddl.Items.Insert(0, new ListItem("Please Select", ""));
if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text))
ddl.SelectedValue = lblValue.Text;
}
}

ASP.NET - Finding Label Control in a GridView

I'm having a problem trying to find a label control that is inside a GridView.
Please see my codes below:
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDate" MaxLength="10" Width="70" />
<asp:ImageButton ID="imgScoreDate" runat="server" ImageUrl="~/images/calendar.gif" />
<ajaxtoolkit:CalendarExtender ID="txtDate_CalendarExtender" runat="server" Enabled="True" Format="MM/dd/yyyy" TargetControlID="txtDate" PopupButtonID="imgDate" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my .cs file:
protected void LoadGridView()
{
//Do something else
foreach (GridViewRow row in MyGridView.Rows)
{
//Tried A
System.Web.UI.WebControls.Label lblName = row.FindControl("lblName") as System.Web.UI.WebControls.Label;
lblName.Text = "Name";
//Tried B
((System.Web.UI.WebControls.Label)row.FindControl("lblName")).Text = "Name";
}
}
I debug this code and it seems to work fine because my breakpoint is being hit each time the debugger runs. It even loops through my foreach block the same count as to how many rows my GridView has.
But I don't understand why my lblName control doesn't get the "Name" text as a value? Am I missing anything here? I tried both //Tried A and //Tried B methods but they both doesn't update my label's text.
Any help would be appreciated!
Thanks! Cheers!
You want to call LoadGridView inside PreRender. Basically, you want to call it after GridView is bound with data.
protected void Page_PreRender(object sender, EventArgs e)
{
LoadGridView();
}
Look at PreRender event of ASP.NET Page Life Cycle.
On your gridview add:
<asp:GridView OnRowDataBound="MyGridView_RowDataBound" ... />
Then define MyGridView_RowDataBound:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
Label l = (Label) e.Row.FindControl("lblName");
}
What I think is happening is the control is not recreated server side in its current spot.
try this
on .aspx page
<asp:GridView ID="MyGridView" runat="server"
onrowdatabound="MyGridView_RowDataBound" .../>
code behind ::
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGridView();
}
}
void LoadGridView()
{
DataTable dt = new DataTable();
// dt= call ur database method to get data
MyGridView.DataSource = dt;
MyGridView.DataBind();
}
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl_Name = (Label)e.Row.FindControl("lblName");
lbl_Name.Text = "Name";
}
}
cheers!

Always getting checkbox as false in grid

i have checkboxes in a grid. I am trying to access them from codebehind and get the data for checked /unchecked rows.But even after the checkboxes being checked I am getting them as Checked property as false only:
Aspx:
<table width="100%">
<asp:GridView ID="grdRequestsPending" runat="server" Width="100%" AutoGenerateColumns="false"
BorderWidth="1px" BorderStyle="Solid" Style="margin-left: 0px" BorderColor="#ffcc00"
RowStyle-BorderColor="#ffcc00" RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px"
GridLines="Both" DataKeyNames="ReqID,ApproverComments" On="grdRequestsPending_ItemDataBound" OnRowDataBound="grdRequestsPending_RowDataBound"
OnPreRender="grdRequestsPending_PreRender">
<RowStyle CssClass="dbGrid_Table_row" />
<HeaderStyle CssClass="dbGrid_Table_Header" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblSelect" Text="Select All" runat="server"></asp:Label><br />
<asp:CheckBox ID="SelectAll" onclick="javascript:checkAllBoxes(this);" TextAlign="Left"
runat="server" />
</HeaderTemplate>
<ItemStyle Width="2%" />
<ItemTemplate>
<asp:CheckBox ID="chkReq" runat="server"/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="7%" />
</asp:TemplateField>
</Columns>
But when I am checking these I am always getting them as false in code behind:
protected void UpdateVMRequestStatusByCapSupLead(int StatusId)
{
try
{
DataTable dt = new DataTable();
dt.Columns.Add("ReqId", typeof(int));
dt.Columns.Add("StatusId", typeof(int));
dt.Columns.Add("ModifiedBy", typeof(string));
dt.Columns.Add("ModifiedDate", typeof(string));
dt.Columns.Add("txtCommentSupLead", typeof(string));
foreach (GridViewRow gr in grdRequestsPending.Rows)
{
CheckBox chk = (CheckBox)gr.FindControl("chkReq");
if (chk.Checked)
{
strReqId = strReqId + grdRequestsPending.DataKeys[gr.RowIndex].Value.ToString() + ',';
TextBox txtCommentSupLead = (TextBox)gr.FindControl("txtCommentSupLead");
dt.Rows.Add(dt.NewRow());
dt.Rows[dt.Rows.Count - 1]["ReqId"] = Convert.ToInt32(grdRequestsPending.DataKeys[gr.RowIndex].Value);
dt.Rows[dt.Rows.Count - 1]["StatusId"] = StatusId;
dt.Rows[dt.Rows.Count - 1]["ModifiedBy"] = Session["UserAccentureID"].ToString();
dt.Rows[dt.Rows.Count - 1]["txtCommentSupLead"] = txtCommentSupLead.Text;
dt.Rows[dt.Rows.Count - 1].AcceptChanges();
dt.Rows[dt.Rows.Count - 1].SetModified();
}
}
I am not getting the problem.I am gettign the control also correctly..
I assume that you're always databinding your GridView and not only if(!Page.IsPostBack)....
So put this in page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataBindControls(); // like GridView etc.
}
}
If you DataBind controls they will lose their changes and ViewState. Even events aren't triggered then. So you should do that only on the first load if EnableViewState="true".
Here is a simple example of populating a checkbox in a gridview and getting the values out on a button click
Default.aspx
<asp:GridView ID="gv"
runat="server"
AutoGenerateColumns="false"
OnRowDataBound="gv_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkReq" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSubmit"
runat="server"
OnClick="btnSubmit_Click"
Text="Submit" />
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create 20 rows
gv.DataSource = Enumerable.Range(1, 20);
gv.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var isCheckedList = new List<bool>();
for(var index = 0; index < gv.Rows.Count; ++index)
{
var chkReq = (CheckBox)gv.Rows[index].FindControl("chkReq");
isCheckedList.Add(chkReq.Checked);
}
//Look at isCheckedList to get a list of current values.
System.Diagnostics.Debugger.Break();
}
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var index = e.Row.RowIndex;
//Strongly Bind Controls
var chkReq = (CheckBox)e.Row.FindControl("chkReq");
chkReq.Text = "Item " + index.ToString();
}
}
Since you did not show all of your code, it could be an issue like Tim Schmelter said or it could be something else. This example provides you with the basics that are needed to retrieve a checkbox value from a grid view.

Dropdown list loses value on gridview RowCommand

I have a DropDownList in a GridView. I am filling the GridView dynamically in GridView RowCreated(). I want to get that DropDownList's value when I click the GridView's Command Button.
In the RowCommand function, I am trying to get the value. However, I can't find the control in that function. Surprisingly, another DropDownList works fine in the same function.
C# code follows:
if (Request.Params["ID"] != null && Request.Params["ID"] != "")
{
FirmID = Convert.ToInt32(Request.Params["ID"]);
//OfficeList = IFARecord.GetOffices(FirmID);
}
if (!IsPostBack)
{
GV_SABAdvisers.DataSourceID = "objectDataSourceSAV";
GV_SABAdvisers.DataBind();
}
protected void GV_SABAdvisers_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Index")
{
int Index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GV_SABAdvisers.Rows[Index];
//Not working
DropDownList Offices = row.FindControl("ddlLocation") as DropDownList;
String officeID = (Offices is DropDownList) ? Offices.SelectedValue : null;
DropDownList ddlJobTitle = row.FindControl("ddlJobTitle") as DropDownList;
if (ddlJobTitle is DropDownList)
{
newAdviserJobTitle.JobTitleID = Convert.ToInt32(ddlJobTitle.SelectedValue);// this works fine.
}
}
}
protected void GV_SABAdvisers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlLocation = e.Row.FindControl("ddlLocation") as DropDownList;
DropDownList ddlJobTitle = e.Row.FindControl("ddlJobTitle") as DropDownList;
DataTable OfficeList = GetOffices(FirmID);
DataTable dtJob = MyTouchstone.Advisers.AdviserFirmJobTitle.AllJobTitle();
foreach (DataRow aOffice in OfficeList.Rows)
{
ddlLocation.Items.Add(new ListItem(aOffice["Address1"].ToString() + ", " + aOffice["Postcode"].ToString(), aOffice["OfficeID"].ToString()));
}
foreach (DataRow aJob in dtJob.Rows)
{
ddlJobTitle.Items.Add(new ListItem(aJob["JobTitle"].ToString(), aJob["JobTitleID"].ToString()));
}
}
}
ASP markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:GridView ID="GV_SABAdvisers" AutoGenerateColumns="false" PageSize = "10"
CssClass="cssPager" AllowPaging="true" AllowSorting="true"
OnPageIndexChanging="GV_SABAdvisers_PageIndexChanging"
runat="server" onrowcommand="GV_SABAdvisers_RowCommand"
onrowcreated="GV_SABAdvisers_RowCreated">
<PagerStyle />
<Columns>
<asp:TemplateField HeaderText="Job Title">
<ItemStyle Width="80px" />
<ItemTemplate>
<asp:DropDownList ID="ddlJobTitle" Width="80px" runat="Server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemStyle Width="200px" />
<ItemTemplate>
<asp:DropDownList ID="ddlLocation" Width="80px" runat="Server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Can anyone help me, please?
I don't see where have you used the CommandName "Index" in your source code.

gridview edit requires to click twice

Why is that I need to click the edit link twice, in a gridview control, before my row enters into edit mode?
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
</Columns>
<ItemTemplate>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == CRUID.Edit.ToString())
{
this.gv.ShowFooter = false;
}
}
You need to avoid rebinding your gridview on each postback.
If not ispostback then
GridView1.DataSource = dt
GridView1.DataBind()
end if
Otherwise you just overwrite Gridview changes.
Great explanation at this link...
http://www.pcreview.co.uk/forums/gridview-two-clicks-needed-enter-place-editing-t3328887.html
Try handling the RowEditing event to set the EditItem Index:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex
}
There are some mistakes in your code as i examined. Correct your code as shown below:
<asp:ObjectDataSource ID="ods" runat="server" TypeName="Employee"
SelectMethod="GetAll" ></asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server" CssClass="styled"
OnRowCommand="gv_RowCommand" DataSourceID="ods"
OnSorting="gv_Sorting" >
<Columns>
...........
<asp:TemplateField>
<ItemTemplate>
<div class='actions'>
<asp:Button ID="btnEdit" runat="server" Text=" Edit " ToolTip="Edit Row" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem,"Id") %>' CausesValidation="False" />
<span style="padding-left:10px"></span>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected override void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.ods.SelectParameters[0].DefaultValue = "";
}
}
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.gv.ShowFooter = false;
}
}
If on using this code the problem does not solve then there may be some problem in your cssclass which you used with your GridView as I have Checked your code on my machine using ObjectDataSource and it works well using edited code.
Also I want to know that what is CRUID in CRUID.Edit.ToString()
and why you used the following line in Page_Load event
this.ods.SelectParameters[0].DefaultValue = "";
as there are no parameter associated with your SelectMethod="GetAll" method used in ObjectDataSource.
May this answer help you.
I guess there is some conflict with the updatepanels on your page..
Try removing all your Update Panels and try again.. It will work for sure.. Mine worked a few seconds ago.. so thought It would be good to share..

Resources