I have two dropdownlist's.DropDownList2(not bound to a datasource) and DropDownList3(bound to a datasource)
On change on input in one dropdownlist some content in the other Dropdownlist should change. For that i had used the logic as.
Autopostback is enabled for both this controls.
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList2.SelectedItem.Text == "Stamp")
{
DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STA"));
DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STM"));
}
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource1" DataTextField="skey" DataValueField="casecode"
AppendDataBoundItems="True" AutoPostBack="True">
<asp:ListItem Selected="True" Value="S">Select</asp:ListItem>
</asp:DropDownList>
Now the problem is when i select DropDownList2.SelectedItem.Text == "Reg" STA and STM are not present. I want STA and STM values back in the dropdownlist on selection of 'Reg'.
When i first load my page and select 'Reg' all the values in DropDownList3(including 'STA' and 'STM') are present and than when i select 'Stamp' the values 'STA' and 'STM' are lost(as shown in the code). Now again when i select 'Reg' this values are not there, i want this values to be present again.
What do i have to do?? Do i have to bind it again to database?
Is there any other logic for it to be used in a different way ?If anyone can help me
You can to bind DropDownList3 everytime DropDownList2 selected index change then only if the value is "Stamp" you remove the values "STA" and "STM" from DropDownList3
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
// Fill DropDownList3 data source and bind it again to restore all the items
FillDataSource(); // This method gets all the data from DropDownList3
DropDownList3.DataBind();
if (DropDownList2.SelectedItem.Text == "Stamp")
{
DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STA"));
DropDownList3.Items.Remove(DropDownList3.Items.FindByText("STM"));
}
...
If you know the values of the dropdown items, you can add them in the else clause, if you don't know the value/text combination you'll have to rebind.
Related
I was curious if I should use a listbox or combobox to look up warehouse part numbers and then fire an event if it is clicked. I want to be able to click that number and then send a specific command out a serial port. I currently use a selection of hyperlinks to do this but there are now to many and a dropdown list would be helpful to select from and fire the same command as if it was the hyperlink.
Here is my code for when a hyperlink is clicked for part HC1_101... could I replace this with a listbox to send the same command? Can I just add the links to the dropdown list?
private void linkLabel_HC1_101_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (serialPort1.IsOpen)
{
var content = new List<byte>();
content.Add(2);
content.AddRange(Encoding.ASCII.GetBytes("01P00101##"));
content.Add(3);
byte[] buffer = content.ToArray();
serialPort1.Write(buffer, 0, buffer.Length);
}
}
Many developers would normally use a DropDownList control. Each item in the list has both a Text property (what the user sees on the screen) and a Value property (which is only seen by your code). Here is a sample:
<asp:DropDownList ID="MyDropDownList" runat="server" OnSelectedIndexChanged="MyDropDownList1_SelectedIndexChanged">
<asp:ListItem Value="1">Item One</asp:ListItem>
<asp:ListItem Value="2">Item Two</asp:ListItem>
<asp:ListItem Value="3">Item Three</asp:ListItem>
</asp:DropDownList>
The text and values in the ListItems can be constructed by your code or from a datasource. And in your server code you have something like this to handle the user making a selection from the list:
protected void MyDropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string value;
value = MyDropDownList.SelectedValue;
// TBD: Construct content from the value, and send it to your serial port.
}
Does this help?
I have a text box and a RadComboBox like this :
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true"></asp:TextBox>
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server" CausesValidation="False"
CollapseDelay="0" Culture="ar-EG" ExpandDelay="0" Filter="Contains" ItemsPerRequest="100"
MarkFirstMatch="true" Width="380px" EnableAutomaticLoadOnDemand="True" EmptyMessage="-emp name-" ShowMoreResultsBox="True" AutoPostBack="True">
</telerik:RadComboBox>
According to the Telerik Documentation
Set a data source to the RadComboBox. Use either DataSourceID or the
DataSource property to do this and set the DataTextField and
DataValueField properties to the respective fields in the data source.
(Note that when using DataSource you must set the property on each
postback, most conveniently in Page_Init.) Set
EnableAutomaticLoadOnDemand to true.
protected void BindEmployees()
{
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
BindEmployees();
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()).Selected = true;//Get exception here Object reference not set to an instance of an object.
}
I find rad_ddl_inner_emp_name.Items.Count = 0 !! before set the selection ! How to fix this problem ?
As I'm sure you aware of by now, the radcombox typeahead functionality searches text via client side interaction and not by value, which is why you can't find the values.
What I would suggest is having a secondary object to search by emp_num (assuming that's the value that will always be entered into the textbox).
For example, create a global variable:
private Dictionary<string, string> Emp_Dict = new Dictionary<string, string>();
Then populate this dictionary when you do your binding. The following code assumes an ienumerable type being returned. If not you may have to populate the dictionary differently. Also, for this to work, you have to include (System.Linq).
var dataSource = Utilities.GetAllEmployees();
Emp_Dict = dataSource.ToDictionary(ex => ex.emp_num, ex => ex.name);
rad_ddl_inner_emp_name.Items.Clear();
rad_ddl_inner_emp_name.DataSource = dataSource;
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
So now we need to use the dictionary on the text changed event.
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
rad_ddl_inner_emp_name.ClearSelection();
if (Emp_Dict.ContainsKey(txt_inner_emp_num.Text.TrimEnd()))
{
rad_ddl_inner_emp_name.SelectedValue = txt_inner_emp_num.Text.TrimEnd();
rad_ddl_inner_emp_name.Text = Emp_Dict[txt_inner_emp_num.Text.TrimEnd()];
}
}
Now when the text changes in the text box, the radcombobox will update when a valid emp_num is entered into the textbox.
The Problem is that the Items only get loaded when you request them!
Set
EnableAutomaticLoadOnDemand="False"
and it will work!
UPDATE:
if you want to use LoadOnDemand set these two Properties and delete the EnableAutomicLoadOnDemand!
EnableLoadOnDemand="True"
EnableItemCaching="True"
UPDATE 2:
Enable ItemCaching isn´t necessary, but it doesn´t hurt!
You do not need to bind data to RadComboBox on every postback unless you disable the view state.
Filter, MarkFirstMatch and EnableAutomaticLoadOnDemand are not useful in your case as you are loading all employees by yourself.
LoadOnDemand basically is when user starts typing inside ComboBox, ComboBox fires ItemsRequested event and retrieves data via ajax.
<asp:TextBox ID="txt_inner_emp_num" runat="server" Width="60px"
ontextchanged="txt_inner_emp_num_TextChanged" AutoPostBack="true" />
<telerik:RadComboBox ID="rad_ddl_inner_emp_name" runat="server"
CausesValidation="False" Culture="ar-EG">
</telerik:RadComboBox>
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
rad_ddl_inner_emp_name.DataSource = Utilities.GetAllEmployees();
rad_ddl_inner_emp_name.DataTextField = "name";
rad_ddl_inner_emp_name.DataValueField = "emp_num";
rad_ddl_inner_emp_name.DataBind();
}
}
protected void txt_inner_emp_num_TextChanged(object sender, EventArgs e)
{
string value = txt_inner_emp_num.Text;
if(!string.IsNullOrWhiteSpace(value))
{
value = value.Trim();
if (rad_ddl_inner_emp_name.Items
.FindItemByValue(txt_inner_emp_num.Text.Trim()) != null)
rad_ddl_inner_emp_name.SelectedValue = value;
}
}
Since you don't have any item in rad_ddl_inner_emp_name.Items you can set txt_inner_emp_num.Text as selected in ddl.
First check if rad_ddl_inner_emp_name.Items count > 0 then set desired text selected. Or you can check if rad_ddl_inner_emp_name.Items.FindItemByValue(txt_inner_emp_num.Text.TrimEnd()) is not null.
I have a ListBox which is populated dynamically from a database in the code behind. I have another button and when i click the button, the button click event will get the all the selected listitem and insert the list item text to the database. I set AutoPostBack as false and EnableViewState is true in the listbox property
The problem is when i click the button , it only see 1 selected item even i select multiple items.Here are the codes. I appreciate your help. I spend 1 day on this issue and not getting anywhere.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadrdlist();
}
}
protected void loadrdlist()
{
((ListBox)TestFormView.FindControl("ListBoxB")).Items.Clear();
foreach (FailureTempRD rd in FailureTempRD.SelectFailureTempRD())
((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ReferenceDesignator));
}
protected void btn_AddRD_Click(object sender, EventArgs e)
{
foreach (ListItem rd in ((ListBox)TestFormView.FindControl("ListBoxB")).Items) //This is where it only see 1 selected item
{
if (rd.Selected == true)
//put selected item to database
}
}
}
Here are both listbox and button
<asp:ListBox ID="ListBoxB" runat="server" SelectionMode="Multiple" ></asp:ListBox>
<asp:Button ID="btn_AddRD" runat="server" CausesValidation="False" onclick= "btn_AddRD_Click" Text="Add" />
Update :
I figure why. When i load the listitem, i need to add ID as listitem value. So change the following code. I test few times and it works as intend.
((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ReferenceDesignator));
To
((ListBox)TestFormView.FindControl("ListBoxB")).Items.Add(new ListItem(rd.ReferenceDesignator, rd.ID));
Try using the GetSelectedIndices Method.
From above link:
Use the GetSelectedIndices method to identify or access the selected
items in the ListBox control. Each element in the returned array
represents the index for a selected list item. You can use the index
values to access the items in the Items collection.
I have a data grid, and data is coming from database, it has combo boxes in status and I want them to be according to their respective values, for example, there is a column of status, it has a combo box: Open and Close, I want it to be changed with respect to the value it has in database table-column, if it has Close written in database table column, combo box should be selected as Close, if it has Open then it should be selected as Open. Please see the image attached.
Thanks for Help in advance.
Assuming that you're using a template column, you can do this:
<asp:TemplateColumn>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Eval("DropDownValueColumn") %>' />
</ItemTemplate>
</asp:TemplateColumn>
If you want to set the SelectedValue in the ItemDataBound event, you can do it like this:
protected void DataGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
DropDownList ddl = e.Item.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
ddl.SelectedValue = DataBinder.Eval(e.Item.DataItem, "DropDownColumnValue").ToString();
}
}
First of all save your data source in viewstate. If datasource is datatable then do like this.
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlList = (DropDownList)e.Row.FindControl("Name_of_DPList");
int i=e.Row.RowIndex;
DataTable dtTable = (DataTable)ViewState["dtPurchaseOrder"];
string str = dtTable.Rows[i]["Name_Of_column"].ToString();//Name of the column in data source that stores the status.
ddlList.items.FindByText(str).Selected=true;
}
}
So I have a country dropdownlist and a state dropdownlist which is being populated dynamically based off of the country chosen. When I click the country the state dropdown gets populated just fine but the problem arises when I click a value (state) from the other dropdown, the list instead of retaining the selected item will go back to the first item of the list and no selectedvalue are displayed.
<td><asp:DropDownList ID="ddlState" runat="server"
DataSourceId="dsStateList"
DataTextField="state_nm"
DataValueField="state_cd"
OnSelectedIndexChanged="ddlState_SelectedIndexChanged"
AutoPostBack="true"
AppendDataBoundItems="true"
Width="160px" OnDataBound="ddlState_OnDataBound">
</asp:DropDownList>
</td>
<asp:DropDownList ID="ddlCountry" runat="server"
DataSourceId="dsCountryList"
DataTextField="COUNTRY_NAME"
DataValueField="COUNTRY_CIA_ID"
OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
OnDataBound="ddlCountry_OnDataBound"
AutoPostBack="true"
AppendDataBoundItems="true"
Width="160px">
</asp:DropDownList>
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
string comboStateCODE = ddlState.SelectedValue;
dsCompanyListParam.Text = comboStateCODE;
ddlCountry.DataBind();
ddlState.DataBind();
}
protected void ddlState_OnDataBound(object sender, EventArgs e)
{
ddlState.Items.Insert(0, "Please Select a State");
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
ddlState.Items.Clear();
dsStateList.SelectParameters["iCountryID"].DefaultValue = ddlCountry.SelectedValue;
dsCompanyListParam.Text = ddlCountry.SelectedValue;
Trace.Warn("ddlCountry_SelectedIndexChanged");
ddlCountry.DataBind();
ddlState.DataBind();
}
protected void ddlCountry_OnDataBound(object sender, EventArgs e)
{
ddlCountry.Items.Insert(0, "Please Select a Country");
}
I presume that somewhere in your Page_Load() you are making a call to a method that populates the dropdown... you need to encapsulate this into an IF !PostBack block:
// somewhere in PageLoad()...
If(!IsPostBack)
{
PopulateDropdown();
}
Using the convention above, the dropdown will only be populated on the first ever page load. What I suspect is happening is that when you make a selection from the other dropdown, the AutoPostBack is executing the Page_Load() method (as it should) and repopulating the dropdowns again.
Using the convention above should help avoid this.
Your state drop down is set to Autopostback - is it possible that your code to populate the country drop down is executing again on postback, thus rendering the selected state invalid because the country dropdown was repopulated
I would remove the ddlCountry.DataBind(); from the ddlState_SelectedIndexChanged event. I don't see why you need to do another DataBind there.
Solved it!
Ok, just so anyone who's stuck with a similar problem and can't find any other areas to look at here's how I fixed the stupid problem.
First of all, I was using a stored procedure and the stored procedure is concatenating the values from two fields. I set the parameters the Integer(4) which I didn't noticed there're a couple of countries with codes of more than 4. So basically, it's returning a NULL selectedvalue which in turn will not generate any value since my onselectedindexchanged method is based off of the selectedvalue and for some reason a NULL is not being processed.
So yeah, check your stored procs and parameter data! :D
Thanks for your time!