Combobox or Listbox? - c#

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?

Related

How to put a label into a checkboxlist from another page for asp.net

I tried doing this on the check box list page:
protected void Page_Load(object sender, EventArgs e)
{
(string)Session["name"] = cbl1.Items.Add;
}
but I don't know how to make it work.
You don't really "put a label into" a check box list from another page.
You might say have a check box list on one page, and you want to pass the selection(s) made in the first page, and pass to the 2nd page.
So, say we have a simple check box list of options on page 1
And a button to jump to the next page.
This markup:
<h3>Hotel Options</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="ID"
DataTextField="HotelOption" >
</asp:CheckBoxList>
<br />
<br />
<asp:Button ID="Button1" runat="server"
Text="Continue to next page" CssClass="btn" OnClick="Button1_Click" />
And code to load this up:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
DataTable rstOptions =
MyRst("SELECT ID, HotelOption FROM tblOptions ORDER BY ID");
CheckBoxList1.DataSource = rstOptions;
CheckBoxList1.DataBind();
}
DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Hotels))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And we now have this:
Ok, so now our code for the button.
We will get + save the above selections, and pass to the next page:
protected void Button1_Click(object sender, EventArgs e)
{
Session["MyItems"] = CheckBoxList1.Items;
Response.Redirect("WebForm2.aspx");
}
Ok, now our markup for the 2nd page.
We have this:
<h3>Hotel Options - on next page</h3>
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataValueField ="Value"
DataTextField="Text" >
</asp:CheckBoxList>
<br />
Now, we saved the "items list" for the Check box list. The item list has a text and value property (we LOSE the colum name information that the data sourced used was).
So, note how the DataValueField="value" and DataTextField="Text" now.
So, this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCheckBox();
}
void LoadCheckBox()
{
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach (ListItem OneItem in MyItems)
{
CheckBoxList1.Items.Add(OneItem);
}
}
And now on 2nd page we have this:
Now it is NOT clear why I can't just bind this passed list directly to the check box list, but I found a foreach loop is required.
Now, it is perhaps not clear, but maybe you ONLY wanted the label text ones selected.
You can do this with this code:
ListItemCollection MyItems = (ListItemCollection)Session["MyItems"];
foreach(ListItem OneItem in MyItems)
{
if (OneItem.Selected)
{
Debug.Print("Label text = " + OneItem.Text);
Debug.Print("Check box value = " + OneItem.Value);
}
}
Output:
Label text = Smoking
Check box value = 1
Label text = Balcony
Check box value = 2
So, keep in mind that a check box list can often have 2 columns of data.
The display "label" or text, or the hidden value.
In my example, the "ID" is the PK value from the database, and I need that.
If you only have one "text" value, and don't care about a hidden database PK value, then often I just set both DataTextField and DataValueField to the SAME column in the database.
And if you using looping, and adding a listitem in code? Then the settings are not the field columns anymore, but Text and Value. You thus still have the ability to have 2 values - the display text, and some key or number value for a checkbox list.
Now perhaps you have two web pages open, and you want to change/set controls in the other web page?
No, you can't do that. Other web pages might say be open to someone's banking web site. You can't mess around with other web pages the user has open, since that would be a MASSIVE security hole, and no one would risk using the world wide web then, right?
Edit: placing the results on a label on the 2nd page
Ok, so the debug.print? That is just a handy debugging way of displaying some code values - only for developers. It really much like using console.log to display value(s) into the console. It certainly not for putting some text into a label (I realy thought that would be crystail clear to you - at a loss as to why you think debug.print has anything of value or is relavent to YOU writing code to put a few text values into a label).
So, ok, on the 2nd page we will have a label and not some check box list.
So, our markup on the 2nd page will now look like this:
<asp:Label ID="Label1" runat="server" Text=""
Font-Bold="true"
Font-Size="Large"
></asp:Label>
And in our page load event, we will have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadLabel();
}
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += ",";
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
So, now on first page, we say select this:
And now on 2nd page, we see this:
Of course, we could change our code to display each choice on a new line,
Say this code:
void LoadLabel()
{
ListItemCollection MyChoices = (ListItemCollection)Session["MyItems"];
// process selection list from
// previous page - shove reuslts into label
string strChoices = "";
foreach (ListItem OneChoice in MyChoices)
{
if (OneChoice.Selected)
{
if (strChoices != "")
strChoices += #"<br/>"; // <-- new line in label
strChoices += OneChoice.Text;
}
Label1.Text = strChoices;
}
}
And now we would see this:
So, you can shove results into that label - separated by ",", or whatever.
Or, you can display the choices on a new line as per last example.

gridview and radio button list on browser back button

On my aspx page there is a RadioButtonList and it contains list items named “additions” and “termination”. Also there two gridview “GV_addition” and “GV_termination”. On selecting the radio button “addition”, then the gridview “GV_addition” will be shown. When item “termination” is selected, then the gridview “GV_termination” will be shown.
On radio button changed event, it is working correctly. But my problem is , when I click browser back button, the radio button selection and corresponding grid view not showing correctly. I got issue, “Gv_termination” is showing when radio button “addition” is selected. This issue is showing only when I click browser back button.
Please find my below code
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Text="addition" Value="addition"> </asp:ListItem>
<asp:ListItem Text="termination" Value="termination"></asp:ListItem>
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList1.SelectedIndex == 0)
{
GV_addition.Visible = true;
GV_termination.Visible = false;
}
else
{
GV_termination.Visible = true;
GV_addition.Visible = false;
}
}
I could not understand why the why the radio button selection and corresponding gridview visiblity is not working on the browsers back button event. Can any one help me to solve this issue?
Please try below steps. For me the same scenario worked.
I could see the values are updating correctly, but the updated radio checked states are not updating in to the UI. So I have set it using javacript on the Onload event of a body.
Add the Onload event on the body.
<body onload="setRadioButonStatus()">
and add the following Javascript.
function setRadioButonStatus() {
var rbtn1 = document.getElementById('RadioButton1');
var rbtn2 = document.getElementById('RadioButton2');
if (rbtn1.hasAttribute("checked"))
rbtn1.checked = true;
if (rbtn2.hasAttribute("checked"))
rbtn2.checked = true;
}
Seems like you aren't creating a "default" scenario. You can do this, and tie the logic together more closely by doing something like this on every Page_Load and leaving it out of your event.
protected void Page_Load(object sender, EventArgs e)
{
GV_addition.Visible = RadioButtonList1.SelectedIndex == 0;
GV_termination.Visible = RadioButtonList1.SelectedIndex == 1;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
}

Dynamically added items don't raise events.(ASP.NET ListBox)

My code is:
private void Add_Items()
{
for (int x = 1; x < 53; x++)
{
ListBox1.Items.Add("Item" + x);
ListBox1.DataValueField = "Value" + x;
}
}
None of these items raises SelectedIndexChanged event when clicked.
Please assist.
Make sure autopostback is enabled, like in this examle:
<asp:ListBox ID="listBoxLocation" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="listBoxLocation_SelectedIndexChanged" EnableViewState="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:ListBox>
Or to dynamically populate:
Protected void Button1_Click (object sender, System.EventArgs e)
{
ListBox1.Items.Add(new ListItem("Carbon", "C"));
ListBox1.Items.Add(new ListItem("Oxygen", "O"));
}
From: http://msdn.microsoft.com/en-us/library/14atsyf5%28v=vs.85%29.aspx
First.
The ListBox1.DataValueField should not be set to every item. This property sets the field on the data object (each row) to capture the value from. Here is the MSDN link for this property http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.datavaluefield(v=vs.110).aspx.
Next, I am assuming you have all the front end code wired up something like.
<asp:ListBox ID="ListBox1" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" runat="server"></asp:ListBox>
This has the selected changed event wired up. However for this control to actually Post the data back you need to provide one more attribute. Add
AutoPostBack="true"
To your control as.
<asp:ListBox ID="ListBox1" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true" runat="server"></asp:ListBox>
This starts the magic. MSDN for AutoPostBack: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback(v=vs.110).aspx
Your code is very vague, and im going to make the assumption that your ListBox has not been linked up to a SelectedIndexChanged event in the correct way.
If you are dynamically creating the ListBox link it up as below:
public void initialize()
{
ListBox lb = new ListBox();
lb.SelectedIndexChanged += lb_SelectedIndexChanged;
}
private void lb_SelectedIndexChanged(object sender, EventArgs e)
{
//Do Selected Index Changed Code Here
}
If you have a view/form with the control on, simply make sure that the ListBox's event has been set or naturally it will not trigger.
*EDIT 1
As noted in other answers your control is required to have PostBack set. You should also be checking the PostBack state of your page to ensure you are not redrawing your controls continuously, as this will keep resetting your Dynamically added controls.

DropDown List resets to the first item and doesn't return a selectedvalue

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!

Dropdownlist in ASP.net C#

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.

Categories