[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1434
  • Last Modified:

Reading htmlSelect items from the C# code behind

I am trying to implement the client side listbox using javascript. I am trying to fill two htmlSelect listboxes and am able to fill the first listbox successfully by feeding the data from a dataset. Here is the code behind:
 
string
js = "";
foreach (DataRow row in dsDropDown.Tables[COUNTRIES].Rows)
{
js = js +
"AddItem('" + lstCountries.ClientID + "', '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
}
Page.ClientScript.RegisterStartupScript(
this.GetType(), "AddItem", js, true);

and here is the javascript function:
 
function
AddItem(selectbox, text, value )
{
var optn = document.createElement("option");
optn.text = text;
optn.value = value;
if(selectbox='lstCountries')
var elSel = document.getElementById('lstCountries');
else if(selectbox='lstCountriesofOrigin')
var elSel = document.getElementById('lstCountriesofOrigin');
elSel.add(optn);
}
and here are the aspx htmlSelect object defined:
 
<p><select id="lstCountries" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px">
</select></p>
<p><select id="lstCountriesofOrigin" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px">
</select></p>

The first htmlSelect listbox named lstCountries is populated successfully. When I tried to populate the second htmlSelect  listbox lstCountriesofOrigin using the same javascript function called from the following code behind loop, I am having problems reading the items from the lstCountries htmlSelect listbox. The items I added to this htmlSelect liatbox using the javascript function in the above code are no longer there and the lstCountries.Items.Count is zero. Here is the code behind I am trying to use:
foreach
(DataRow row in dsSearchResults.Tables[COO].Rows)
{
foreach (DataColumn column in dsSearchResults.Tables[COO].Columns)
{
if (column.ColumnName.ToString() == "CountryNM")
{
for (int i = 0; i < lstCountries.Items.Count; i++)
{
if (lstCountries.Items[i].Text == row["CountryNm"].ToString())
{
js = js +
"AddItem('" + lstCountriesofOrigin.ClientID + "', '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
break;
}
}
}
}
}
Page.ClientScript.RegisterStartupScript(
this.GetType(), "AddItem", js, true);
Any ideas why I am not getting the already added items in the lstCountries listbox? Why are they lost and what is the way to get the added items info in the code behind?
0
skaleem1
Asked:
skaleem1
  • 3
  • 2
1 Solution
 
magicdlfCommented:
Let me have a guess. You have a button and need to click the button to populate the second listbox, right? If the button is server side, your page will be refreshed, that's why your data in the first listbox is lost. I am not sure if this is your case.
0
 
skaleem1Author Commented:
This is one of the issues I am going to face once I reach that step. Currently, my issue is regarding the fact that the items in the first htmlSelect listbox populated with data through client-side javascript are lost when I try to access the same htmlSelect listbox through my C# codebehind. Does it make sense?
0
 
magicdlfCommented:
I am still not sure what do you want exactly. Did you try to use the server side controls instead of the client side listbox? I think your problem is that you need to find a way to make the data persists while you are refreshing the form (which will call your C# codebehind). Am I right?
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
skaleem1Author Commented:
magicdlf,

As you can see in the code, I am using the htmlSelect control which is a client side html control used as a substitute for the server side asp listbox control. The reason I chose the client side htmlSelect control is to avoid the annoying postbacks that always happen when using server controls such as listbox. Everytime you select an item from the server side listbox control or try to add remove items from it, a postback occurs that is annoying to the users. I want to avoid this. In order to implement the client side htmlSelect control, I first added the items fed from a dataset as shown in the following block of code:

foreach (DataRow row in dsDropDown.Tables[COUNTRIES].Rows)
                {
                    js = js + "AddItem('" + lstCountries.ClientID + "',  '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
                }

                Page.ClientScript.RegisterStartupScript(this.GetType(), "AddItem", js, true);

The java script function AddItem called from the loop above adds the items to the htmlSelect control as follows:

function
AddItem(selectbox, text, value )
{
var optn = document.createElement("option");
optn.text = text;
optn.value = value;
if(selectbox='lstCountries')
var elSel = document.getElementById('lstCountries');
else if(selectbox='lstCountriesofOrigin')
var elSel = document.getElementById('lstCountriesofOrigin');
elSel.add(optn);
}

Here is the html control:

<p><select id="lstCountries" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px">          
        </select></p>
        <p><select id="lstCountriesofOrigin" size="10" runat="server" style="WIDTH: 176px; HEIGHT: 128px">          
        </select></p>


The issue I am having is that the items added to the htmlSelect control in the above code do not seem to persist when I try to reference those items from the code behind to add items to another htmlSelect as shown below:

foreach
(DataRow row in dsSearchResults.Tables[COO].Rows)
{
foreach (DataColumn column in dsSearchResults.Tables[COO].Columns)
{
if (column.ColumnName.ToString() == "CountryNM")
{
for (int i = 0; i < lstCountries.Items.Count; i++)
{
if (lstCountries.Items[i].Text == row["CountryNm"].ToString())
{
js = js +
"AddItem('" + lstCountriesofOrigin.ClientID + "', '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
break;
}
}
}
}
}
Page.ClientScript.RegisterStartupScript(
this.GetType(), "AddItem", js, true);

The line of code above shows that lstCountries.Items.Count  is zero, which should not be the case as I have just added items to this lstCountries control through javascript above.

I hope this time I have explained better, what do you think?




0
 
Solar_FlareCommented:
the problem that you have here is that when a browser posts back, it only sends the value of the currently selected item in a select control - this means that there is no possible wayfor the server to know what items were added in the client script. Normally asp.net gets around this by storing all the select options of an asp:dropdownlist in the page veiwstate, this way when the page posts back the server can recreate the items in the dropdownlist from the viewstate, and also knows which option was selected as that is the value that the browser posted back.

you have 2 ways that you can make all the option values available on the server:

1. Use asp:dropdownlist and disable the autopostback, and add all items to it server-side so they are in the viewstate.
2. Use a bunch of hidden inputs that you add to your page in your javascript, then read these manually in your code

the client-side javascript option is a whole lot more work, so unless you *really* need to do this client side, I would suggest the first option.

in client side javascript:

function addOption(...)
{
   var h = document.createElement('input');
   h.type = 'hidden';
   h.name = 'addedOption1_value';
   h.value = optionValue;
   document.getElementById('someContainerElementForPuttingNewElements').appendChild(h);


}


in server side code

if(Request.Form["addedOption1_value"] != null)
{ //yes option1 was added
   string addedValue = Request.Form["addedOption1_value"];
   do something

}

Open in new window

0
 
skaleem1Author Commented:
Solar_Flare:

Thanks for your reply. This is exactly the case however I have now been able to maintain a hashtable on the server side to utilize the values for the listitem I added. Here is the code modified on the code behind:

Hashtable hshTableCountries = new Hashtable();
            Hashtable hshTableCountriesofOrigin = new Hashtable();

            string js = "";
            foreach (DataRow row in dsDropDown.Tables[COUNTRIES].Rows)
            {
                js = js + "AddItem('" + lstCountriesAll.ClientID + "',  '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
                hshTableCountries.Add(row["CountryID"].ToString(), row["CountryNM"].ToString().Replace("'", ""));
            }

Below I am using the hash table to retrieve the values I added to the html select listbox:

foreach (DataRow row in dsSearchResults.Tables[COO].Rows)
            {
                foreach (DataColumn column in dsSearchResults.Tables[COO].Columns)
                {
                    if (column.ColumnName.ToString() == "CountryNM")
                    {
                        for (int i = 1; i < hshTableCountries.Count; i++)
                        {
                            if (hshTableCountries[i.ToString()].ToString() == row["CountryNm"].ToString())
                            {
                                js = js + "AddItem('" + lstCountriesofOrigin.ClientID + "',  '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
                                hshTableCountriesofOrigin.Add(row["CountryID"].ToString(), row["CountryNM"].ToString().Replace("'", ""));
                                js = js + "RemoveItem('" + lstCountriesAll.ClientID + "',  '" + row["CountryNM"].ToString().Replace("'", "") + "', '" + row["CountryID"].ToString() + "'); ";
                                break;
                            }
                        }
                    }
                }
            }

Thanks a lot anyways and because your reply answers the point, I will give you the points.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now