Dropdownlist Selected value in postback - c#

I have 2 dropdownlists(ddl1,ddl2) and a gridview with 2 dropdown lists(gddl1,gddl2). On SelectedIndexChanged event of ddl1 am changing SelectedIndex of gddl1 in postback.
My problem is
ddl1.databind() occurs at a button's click event. So once selectedindex of ddl1 changes, the selected value losts and returns back to initial value.
I cant use !IsPostback because am binding ddl1 on button click.
How can I retain ddl1 and ddl2 selected index.?
protected void btnProceed_Click(object sender, EventArgs e)
{
if(ddlLocation.SelectedIndex > -1) {
empDS = ws_service.GetEmpList(ddlLocation.SelectedValue, ((ddlDept.SelectedValue == "All") ? "" : ddlDept.SelectedValue), ((ddlGrade.SelectedValue == "All") ? "" : ddlGrade.SelectedValue));
appraiserDS = ws_service.GetAppList();
grdDetails.DataSource = empDS.Tables[ 0 ].DefaultView;
grdDetails.DataBind();
ddlAppraiserAll.DataSource = appraiserDS.Tables[ 0 ].DefaultView;
ddlAppraiserAll.DataTextField = "APPRAISER_NAME";
ddlAppraiserAll.DataValueField = "APPRAISER_ID";
ddlAppraiserAll.DataBind();
}
}
protected void ddlAppraiserAll_SelectedIndexChanged(object sender, EventArgs e)
{
foreach(GridViewRow gvRow in grdDetails.Rows) {
Control ctrl = gvRow.FindControl("ddlAppraiserId");
DropDownList ddl = ctrl as DropDownList;
if(ddl != null)
ddl.SelectedIndex = ddlAppraiserAll.SelectedIndex;
}
}

The issue here is synchronization and its where you get it and where you bind it, but you can also direct get the value using the Request.Form.
Request.Form[DropDownListID.UniqueID]

I'm not sure if i understood your problem since it's difficult to see what's ddl1, ddl2, gddl1 and so on and when each event is handled.
But my guess is:
DataBind your GridView in btnProceed_Click
Bind the two DropDownLists of the GridView only in RowDataBound
Then your "GridView-DropDownLists" are always up-to-date according to the selected value of ddl1

you can retain ddl1 and ddl2 selected index by storing them in viewstate as properties.
private string ddlSelectedIndex
{
set { ViewState["SelectedIndex"] = value; }
get { return ViewState["SelectedIndex"] == null ? string.Empty : ViewState["SelectedIndex"].ToString(); }
}
The above property is in string, you can create an int property in similar way or use the same and cast index as string. Your selected index will be retained on subsequent postbacks.

Related

datagrid selected index gives troubles

I have a datagrid that I fill with data from a database.
When I click on a row, I call the GotFocus method and try to make a button visible if certain requirements are met.
private void dtgVerkoopsdocumenten_GotFocus(object sender, RoutedEventArgs e)
{
DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
if (row.soort2 == "Factuur")
{
btnBoeking.IsHitTestVisible = true;
btnBoeking.Opacity = 1;
}
else
{
btnBoeking.IsHitTestVisible = false;
btnBoeking.Opacity = 0.5;
}
}
This gives me an error.
Index was out of range. Must be non-negative and less than the size of the collection.
Now when I call the code but from a button click it does it how it's supposed to work.
private void tester_Click(object sender, RoutedEventArgs e)
{
DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
test.Content = row.soort2;
if (row.soort2 == "Factuur")
{
btnBoeking.IsHitTestVisible = true;
btnBoeking.Opacity = 1;
}
else
{
btnBoeking.IsHitTestVisible = false;
btnBoeking.Opacity = 0.5;
}
}
Why is this?
Why dont you use DataGrid SelectedIndexChanged event?
Wyy use GotFocus that doesnt tell you if user even made a selection to start with,
DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
Called from gotfocus will fail as you have nothing selected besides having no error check in place to check if selection,
If you use Selection changed events you know the user has made selection changes there are a number of events for selection
before access selected items by index you need to check selected item count is grater than zero condition.
Because dtgVerkoopsdocumenten.SelectedItems are empty and GotFocus event raise before SelectedItemChanged event so we are not sure the dtgVerkoopsdocumenten.SelectedItems have any item or not.
You can check dtgVerkoopsdocumenten.SelectedItems before do anything.
if (dtgVerkoopsdocumenten.SelectedItems != null &&
dtgVerkoopsdocumenten.SelectedItems.Count > 0)
{
DataItem row = (DataItem)dtgVerkoopsdocumenten.SelectedItems[0];
...
}

How do I Grab Selected Index on two Dropdownlist's OnSelectedIndexChanged?

I am trying to use two DropDownLists to filter data. I set both of the OnSelectedIndexChanged Equal to the method below. The problem is it is only grabbing the SelectedIndex of the DDL that is changed. Example: if i choose a option in DDL1 it grabs that value and doesnt grab the value of DDL2. They both have the same OnSelectedIndexChanged i figured it would grab the current value of both. Is there a way to make it look at both DDL Controls?
protected void BrandsList_SelectedIndexChanged(object sender, EventArgs e)
{
int DDLcatId = CategoriesList.SelectedIndex;
int DDLBraId = BrandsList.SelectedIndex;
IQueryable<Product> DDLprodResult = GetProductsDDL(DDLcatId, DDLBraId);
if(DDLprodResult == null)
{
}
else
{
CatLab.Text = DDLprodResult.ToList().Count().ToString();
productList.DataSource = DDLprodResult.ToList();
productList.DataBind();
}
}
Your code should work. Of course only one can be changed if you have set AutoPostBack="true"(default is false) on both. But you should get the correct SelectedIndex anyway in the handler.
So i will guess: you are databinding the DropDownLists on every postback. Do this only if(!IsPostBack), otherwise you always overwrite changes with the original values.
So for example in Page_Load:
protected void Page_Load(Object sender, EvengtArgs e)
{
if(!IsPostBack)
{
// DataBind your DropDownLists
}
}

How do I populate a dropdownlist based on a selection from another dropdownlist?

protected void ddlEnvironment_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlEnvironment.SelectedIndex == 0)
{
ddlServers.Items.Add("item1");
}
if (ddlEnvironment.SelectedIndex == 1)
{
ddlServers.Items.Add("item2");
}
if (ddlEnvironment.Text == "Production")
{
}
}
The above is not working. When I make a selection on ddlEnvironment and it is the first item on the list (index 0), the other dropdownlist is not upading with "item1". Why?
There could be different reasons by default dropdown list do no do postback.
Check if you have AutoPostBack="true"
You bind the ddlEnvironment in !Page.IsPostBack block so that it maintains its state on postback
if(!Page.IsPostBack)
{
ddlEnvironment.AuutoPostBack = true;
ddlEnvironment.DataSource = datasource;
ddlEnvironment.DataBind();
}
I assume you have AutoPostBack=true - right?
If you're initializing ddlEnvironment in your Page_Load() event handler, it's being reset on postback.
You need to do something like this:
If (!Page.IsPostback)
{
// initialize ddlEnvironment here
}

selected index of DDL is always equal to Zero in asp .net

I have a Program Class, with properties as Id, ProgramName,ShortName and Code, im my app
I have a ASP DDL like
<asp:DropDownList ID="DDLProgram" runat="server"
OnSelectedIndexChanged ="OnDDLProgramChanged" AutoPostBack = "true">
</asp:DropDownList>
My OnDDLProgramChanged method is defined as
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
List<CcProgramEntity> programEntities = GetAllPrograms();
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
//My Problem goes here
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
My list is getting all the records correctly, I have checked it. But whenever I am changing an item in the DDL, the selected index in not changing. The selected index is remaining zero.Therefore, I am not being able to get the code of other items but the 0 index's item.
Can anyone help me in this case?
You are binding the data again in your selectedIndex Change event and it will reset your current SelectedIndex after rebinding. You don't need to rebind the data to your dropdown in SelectedIndex Change Event
It should be like..
protected void OnDDLProgramChanged(object sender, EventArgs e)
{
string programCode = programEntities[DDLProgram.SelectedIndex].Code;
}
You have to bind data to the DropDownList on page load method
if (!IsPostBack)
{
DDLProgram.DataSource = programEntities;
DDLProgram.DataTextField = "Shortname";
DDLProgram.DataValueField = "Id";
DDLProgram.DataBind();
}
Otherwise it will bind data everytime and hence clear the selection
Why are you assigning the DataSource in OnDDLProgramChanged, this would be resetting the selection you make.

Asp.net Gridview - Why Are DataRowBound changes Lost on sort?

I am making conditional formatting changes to the data in my gridview using a RowDataBound event:
void gvReg_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime lastUpdate DateTime.Parse(DataBinder.Eval (e.Row.DataItem, "LAST_UPDATE");
if (lastUpdate < DateTime.Today.AddMonths(-1))
{
Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate";
hypLastUpdate.CssClass = "Error";
hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com";
}
}
}
This works, and sets the proper CssClass to the hyperlink (which makes it a jarring shade of bold red), but once the gridview is sorted (via the user clicking a column heading) the css class is reset on hypLastUpdate and it loses both it's style and associated NavigateUrl property.
The control hypLastUpdate is contained in a template field in a gridview, and it's text value is databound to a field called "LAST_UPDATE".
Is this a planned behavior (is sorting supposed to break the conditional formatting done in RowDataBound events?) or is there something I can check to make sure I am not doing something incorrectly?
I am not using the DataBind method anywhere in the code behind, and viewstate is turned on for the gridview in question.
--EDIT--
It ended up being a mistake in event handling.
I was doing:
gvReg.Sorted += {SomeEventHandler}
Inside of the page load event, but only when it wasn't a postback. This function called gvReg.DataBind after the grid view was sorted. I removed the handler wire up and instead added the event handler function to the OnSorted event. I guess assigned delegates to a gridview are not saved in ViewState between callbacks?
Hi here is a quick example of what I meant on my comment. This is the only way i could think of it:
protected void gvReg_Sorting(object sender, GridViewSortEventArgs e)
{
GridView gridView = (GridView)sender;
if (e.SortExpression.Length > 0)
{
foreach (DataControlField field in gridView.Columns)
{
if (field.SortExpression == e.SortExpression)
{
cellIndex = gridView.Columns.IndexOf(field);
break;
}
}
if (pSortExpression != e.SortExpression)
{
pSortDirection = SortDirection.Ascending;
}
else
{
pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
}
pSortExpression = e.SortExpression;
}
//Retrieve the table from the database
pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
List<Partners> partnerList = GetPartnerList();
gvReg.DataSource = partnerList;
gvReg.DataBind();
}

Categories

Resources