I already have an event handler for a button that generates an excel report. (ExportExcel(filename); is the method that generates the excel report FYI) So that's fine and dandy. What I'm trying to do now is refresh the dropdown list so it reflects what the correct Dropdown selection is.
I got it to set the dropdown list to the 0th index but the dropdown list doesn't change for some reason. So I think I need to somehow individually reset the dropdown list.
Here's some code below. (I left in some comments and Debug.WriteLine()'s to show my thought process)
protected void GenerateButton1(object sender, EventArgs e)
{
// CustomerDropdown.ClearSelection();
// CustomerDropdown.Items.Clear();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
//////////
// Below is resetting the CustomerDropdown list.
ViewState["DropDownIndexSelection"] = CustomerDropdown.SelectedItem.Value.Trim();
DataSet dataSet = (DataSet)ViewState["DropDownListDs"];
var filename = "Customer ID - " + DateTime.Now + ".xlsx";
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.Items.FindByValue("Please select").Selected = true;
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == false);
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == true);
return;
}
How can I set the Dropdown back to "Please select" after running the ExportExcel(filename) method? I think basically what I'm asking is how do I refresh the CustomerDropdown after setting the selection to "Please select"
CustomerDropdown.SelectedIndex = 0;
after that it will select the 0th index selection, which is "Please select."
Have you tried adding to your code:
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.SelectedIndex=0; ---> Possible solution
?
Got from: Reference
Related
I have two combo box ( say cbo_zone & cbo_floor ) which are having table as the data source
private void load_cbo_zone()
{
clz_Common_References ccr = new clz_Common_References ();
DataTable dt_zone = ccr.get_zone_detail();
cbo_zone.DataSource = dt_zone;
cbo_zone.ValueMember = "ID";
cbo_zone.DisplayMember = "zone";
cbo_zone.SelectedIndex = -1;
}
`
private void load_cbo_floor()
{
int ID_zone_ref = Convert.ToInt16(cbo_zone.SelectedValue);
clz_Common_References ccr = new clz_Common_References();
DataTable dt_flr = ccr.get_floor_data_fr_Ref_IDZone(ID_zone_ref);
cbo_floor.DataSource = dt_flr;
cbo_floor.DisplayMember = "Floor";
cbo_floor.ValueMember = "ID";
cbo_floor.SelectedIndex = -1;
}
` . I wrote the code to update the cbo_floor as following .
private void cbo_zone_SelectionChangeCommitted(object sender, EventArgs e)
{
load_cbo_floor();
}
Now I need to update the cbo_zone & cbo_floor when I click a data row of datagridview .
int ref_area_id, ref_floor_id, ref_zone_id;
int.TryParse(dt_issued_mat.Rows[0][11].ToString(), out ref_area_id);
DataTable dt_area_detail = ccr.get_area_data_fr_area_id(ref_area_id);
int.TryParse(dt_area_detail.Rows[0][2].ToString(), out ref_floor_id);
DataTable dt_floor_detail = ccr.get_floor_data_fr_floor_id(ref_floor_id);
int.TryParse(dt_floor_detail.Rows[0][2].ToString(), out ref_zone_id);
DataTable dt_zone_detail = ccr.get_zone_data_fr_zone_id(ref_zone_id);
after that using
cbo_zone.Text = dt_zone_detail.Rows[0][1].ToString();
cbo_floor.Text = dt_floor_detail.Rows[0][1].ToString();
I was able to display the values on the combo boxes but once I tried to get the cbo_floor.SelectedValue code doesn't work .
Then I was able to get the relevant SelectedIndex by using ,
int index = cbo_zone.FindString(dt_zone_detail.Rows[0][1].ToString());
cbo_zone.SelectedIndex = index ;
still the combo box shows nothing & "cbo_zone.SelectedValue" doesn't
show a value.my target is to get the cbo_floor.SelectedValue .
Please help .
Instead of cbo_zone.Text = dt_zone_detail.Rows[0][1].ToString();
cbo_floor.Text = dt_floor_detail.Rows[0][1].ToString();
Use
cbo_zone.Items.Add( dt_zone_detail.Rows[0][1].ToString());
cbo_floor.Items.Add ( dt_floor_detail.Rows[0][1].ToString());
First working with indexes is not a good idea. You have the value, use them. Using the index will cause you trouble.
cbo_zone.SelectedValue = myValue.ToString();//find the value from your data
Secondly for selecting the floor, you need to fill it with the relevant values first, since it already has the data for the last selection.
load_cbo_floor();
cbo_floor.SelectedValue = myValue.ToString();//find the value from your data
Ok, very dumb question but i haven't really found an answer on internet.
I have multiple comboboxes on a form. The binding of each combobox is on form_load.
When the form loads, the first item is selected on the form. This is obvious, but I don't want this. So i used in the form_load the following code:
private void InvoiceView_Load(object sender, EventArgs e)
{
// Bind list of customers to combobox
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
CustomerComboBox.DisplayMember = "CustomerName";
CustomerComboBox.ValueMember = "CustomerId";
// Bind list of products to combobox
productCombobox.DataSource = invoicePresenter.getProducts();
productCombobox.DisplayMember = "ProductName";
productCombobox.ValueMember = "ProductId";
// Bind list of vat codes to combobox
vatComboBox.DataSource = invoicePresenter.getTaxCodes();
vatComboBox.DisplayMember = "taxCodeShortDescr";
vatComboBox.ValueMember = "taxCodeId";
// Set comboboxes empty
CustomerComboBox.SelectedItem = null;
productCombobox.SelectedItem = null;
vatComboBox.SelectedItem = null;
}
This works. But the textboxes are still giving me the data of the first item ? My guess is because its in the selectedIndexChanged. But i have no clue what to use else.
If I put the combobox.selectedIndex = -1; I face the same issue.
the code:
private void CustomerComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Bind the selected customer itemvalues to the texboxes
txtCustomerName.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerName.ToString();
txtAddress.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerAddress.ToString();
txtPostalCode.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerPostalCode.ToString();
txtCity.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCity.ToString();
txtCountry.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCountry.ToString();
txtVatNumber.Text = ((tbl_customer)CustomerComboBox.SelectedItem).CustomerCountryCode.ToString() + ((tbl_customer)CustomerComboBox.SelectedItem).CustomerVat.ToString();
}
One would think, because im using selecteditem in the textbox binding, it would be null also. But this is not the case.
Interestingly, seems like you've hit one of the WF data binding quirks. The problem is caused by the fact that the CurrencyManager class which maintains every list data source does not allow setting the Position property to -1 (thus Current to null) when the list count is not zero. Since the ComboBox is synchronizing the SelectedIndex with the CurrencyManager.Position, this effectively prevents having an unselected item.
As a workaround, if the data bound mode of the list portion is not essential for you, replace the line
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
with
foreach (var customer in invoicePresenter.getCustomers())
CustomerComboBox.Items.Add(customer);
Do the same for the other comboboxes that need such behavior.
You can remove the handler for the SelectedIndex_Changed event of combobox, bind data, then add the handler back. like this :
private void InvoiceView_Load(object sender, EventArgs e)
{
this.CustomerComboBox.SelectedIndexChanged -= new EventHandler(CustomerComboBox_SelectedIndexChanged);
this.productCombobox.SelectedIndexChanged -= new EventHandler(productCombobox_SelectedIndexChanged);
this.vatComboBox.SelectedIndexChanged -= new EventHandler(vatComboBox_SelectedIndexChanged);
// Bind list of customers to combobox
CustomerComboBox.DataSource = invoicePresenter.getCustomers();
CustomerComboBox.DisplayMember = "CustomerName";
CustomerComboBox.ValueMember = "CustomerId";
// Bind list of products to combobox
productCombobox.DataSource = invoicePresenter.getProducts();
productCombobox.DisplayMember = "ProductName";
productCombobox.ValueMember = "ProductId";
// Bind list of vat codes to combobox
vatComboBox.DataSource = invoicePresenter.getTaxCodes();
vatComboBox.DisplayMember = "taxCodeShortDescr";
vatComboBox.ValueMember = "taxCodeId";
this.CustomerComboBox.SelectedIndexChanged += new EventHandler(CustomerComboBox_SelectedIndexChanged);
this.productCombobox.SelectedIndexChanged += new EventHandler(productCombobox_SelectedIndexChanged);
this.vatComboBox.SelectedIndexChanged += new EventHandler(vatComboBox_SelectedIndexChanged);
}
I want to load tables from database in datagridview based upon selected combobox item. I'm using entity framework. My code is as follows:
private void btnCRUDLoadTable_Click(object sender, EventArgs e)
{
//prompt user when "Load Table" button is clicked without selecting any database or table or user
if (cboSelectDB.SelectedIndex <= -1 || cboSelectUser.SelectedIndex <= -1 || cboSelectTable.SelectedIndex <= -1)
{
MessageBox.Show("Please Select Database, User and Table First");
}
else
{
//load data according to combobox selection in datagridview
if (cboSelectUser.Text.ToString() == "User_name")
{
var context = new NameEntities();
BindingSource bi = new BindingSource();
//here, instead of putting tablename is there a way to put
//combox item name? I have tried combobox.Text.ToString(),
//but it doesn't work, shows error
bi.DataSource = context.TableName;
dgvLoadTable.DataSource = bi;
dgvLoadTable.Refresh();
}
}
}
Any help will be appreciated, thanks.
You can use reflation to set the table name dynamically. As below.
var context = new NameEntities();
BindingSource bi = new BindingSource();
//here, instead of putting tablename is there a way to put
//combox item name? I have tried combobox.Text.ToString(),
//but it doesn't work, shows error
var TableName = combobox.Text.ToString();
bi.DataSource = context.GetType().GetProperty(TableName).GetValue(obj, null);
dgvLoadTable.DataSource = bi;
dgvLoadTable.Refresh();
The TableName must be the property name created in NameEntities corresponding to the database table.
I have three drop down menus that are using a store Procedure to populate my gridview. I need the first facility DropDown to give different options in the second source type dropdown depending on what facility is selected. Some facility's need to see all options and some only 1 or 2. I am unsure how to go about this.
Here is the code for the dropdowns and the store precedure.
Any help would be greatly appreciated
private void BindGrid()
{
//set up arguments for the stored proc
int? FacilityID = (ddlFacility.SelectedValue.Equals("-1")) ? (int?)null : int.Parse(ddlFacility.SelectedValue);
int? SourceTypeID = int.Parse(ddlSource.SelectedValue);
int? StatusTypeID = int.Parse(ddlStatusType.SelectedValue);
//bind
ObjectResult<models.MS_spGetMatchCross_Result> ds = this.DataLayer.model.MS_spGetMatchCross(FacilityID, SourceTypeID, StatusTypeID);
gvResults.DataSource = ds;
gvResults.DataBind();
}
private void ResetForm()
{
try
{
//facility dropdown
ddlFacility.Items.Clear();
ddlFacility.DataSource = this.DataLayer.model.MS_spGetFacilityInfo(null).OrderBy(x => x.FacilityName);
ddlFacility.DataTextField = "FacilityName";
ddlFacility.DataValueField = "FacilityID";
ddlFacility.DataBind();
ddlFacility.Items.Insert(0, new ListItem("Select a facility...", "-1"));
//SourceType dropdown
ddlSource.Items.Clear();
ddlSource.DataSource = this.DataLayer.model.SourceTypes;
ddlSource.DataTextField = "Description";
ddlSource.DataValueField = "SourcetypeID";
ddlSource.DataBind();
//Match Status dropdown
ddlStatusType.Items.Clear();
ddlStatusType.DataSource = this.DataLayer.model.StatusTypes;
ddlStatusType.DataTextField = "Description";
ddlStatusType.DataValueField = "StatusTypeID";
ddlStatusType.DataBind();
BindGrid();
}
catch (Exception ex)
{
this.SetMessage(ex.ToString(), PageMessageType.Error);
AISLogger.WriteException(ex);
}
}
A very straightforward, though not exactly elegant, way would be to handle the DropDownList's OnSelectedIndexChanged event. For that to work, you'd have to make sure that each DDL whose selection will affect the contents of another DDL has the AutoPostBack property set to true (this ensures when something in the DDL changes, the page will cause a postback, allowing you to handle the change in server-side code).
In your first DropDownList's OnSelectedIndexChanged event handler (in the code-behind), you'll have the following code:
// Handle selected item or selected index
if(ddl1.SelectedItem.Text=="Selection1")
{
// Get items for DDL2
var items=GetDataForDdl2();
// Bind the data
DDL2.DataSource=items;
DDL2.DataBind();
}
You'd have similar logic for DDL2's SelectedIndexChanged event handler to then bind the items of DDL3, and so on.
For something that works nicely out of the box, check out the ASP.NET AJAX AjaxControlToolkit's CascadingDropDown: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx
i am trying to create a edit profile page so when the page loads first i am filling all text boxes values as the value present in the database for the particular user.i am doing this using the code:
DBconn obj1 = new DBconn();
String sql1 = "select* from users where user_id='" + Session["user_id"].ToString() + "'";
DataTable dt = new DataTable();
dt = obj1.getdatatable(sql1);
if (dt.Rows.Count > 0)
{
referal_id.Text = dt.Rows[0]["referal_id"].ToString();
name.Text = dt.Rows[0]["name"].ToString();
password.Text = dt.Rows[0]["password"].ToString();
email.Text = dt.Rows[0]["email"].ToString();
mobile.Text = dt.Rows[0]["mobile"].ToString();
city.Text = dt.Rows[0]["city"].ToString();
state.Text = dt.Rows[0]["state"].ToString();
pincode.Text = dt.Rows[0]["pincode"].ToString();
sec_ques.Text = dt.Rows[0]["securityq"].ToString();
answer.Text = dt.Rows[0]["answer"].ToString();
age.Text = dt.Rows[0]["age"].ToString();
gender.Text = dt.Rows[0]["gender"].ToString();
user_id.Text = dt.Rows[0]["user_id"].ToString();
address.Text = dt.Rows[0]["address"].ToString();
date_of_joining.Text = dt.Rows[0]["date_of_joining"].ToString();
user_type.Text = dt.Rows[0]["user_type"].ToString();
}
now this is filling all the text boxes with the values .
when user edits some values in some textbox and resubmits the form the database is getting updated implementing the code:
protected void LinkButton1_Click(object sender, EventArgs e)
{
int i;
DBconn obj2 = new DBconn();
String sql2 = "update users set name='"+name.Text+"',address='"+address.Text+"',age='"+age.Text+"',gender='"+gender.Text+"',email='"+email.Text+"',mobile='"+mobile.Text+"',securityq='"+sec_ques.Text+"',answer='"+answer.Text+"',city='"+city.Text+"',state='"+state.Text+"',pincode='"+pincode.Text+"' where user_id='"+Session["user_id"].ToString()+"'";
i = obj2.executeDML(sql2);
if (i > 0)
{
Label1.Visible = true;
Image2.Visible = true;
Label1.Text = "Updated successfully!";
}
else
{
Label1.Visible = true;
Label1.Text = "Oops Update was unsuccessfull!";
}
}
the problem is the database is getting updated with the previous values which was already present in the database.when i used watchpoints i found the sql statement gets loaded with the textbox values which i binded using the above database code but its not fetching the values which the user edits.
plz help.
Hey Robin,
Please check whether the code is placed under the !IsPostback condition or not.
Please bind the values under this if loop.
if(!IsPostback)
{
// Bind values
}
do this on the page load.
The values must only be bound for the first time the page is load.
In your case it seems the values to the text boxes are bound for each and every time it is loaded(even in the postback also the values are loaded.)
So, in page load you must check the condition whether the page is postback or not.
Thus add this condition while binding the values in page load.
if(!IsPostback)
Firstly check the location from where u r calling the mathod for binding values...
put it on
Page.isPostback
so it will not change the value at posting time then when u will save it the value will change
the value must be changing when u click on button and page is again loading.