ListItem.Selected returning false - c#

I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}

The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.

Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?

To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.

UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine

Related

Filtering of combobox - weird behaviour

I have a combobox in my WinForms application in which you can search for a string and results are filtered accordingly, but it seems to behave very strangely. I am searching for "Coo" and I get a very long list of products that do not contain the string "coo" (http://prntscr.com/pr54rs). However, when I type in "coor" and then press backspace, leaving me with "coo" again, the list of results is different (http://prntscr.com/pr55ef)
I am using the "KeyPress" event handler to search in the combobox. The code looks like this
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
comboBox1.Items.Clear();
listNew.Clear();
var source = new AutoCompleteStringCollection();
foreach (var item in listOnit)
{
if (item.ToLower().Contains(this.comboBox1.Text.ToLower()))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
}
Am I doing something wrong? The list is populated from a database
string sqlProducts = "SELECT Description FROM stocktake_products WHERE stocktake_id = '" + stocktakeID.stocktake_id + "' AND (PLUProdCode IS NULL OR PLUProdCode = '');";
MySqlCommand cmdProduct = new MySqlCommand(sqlProducts, conn);
cmdProduct.CommandTimeout = 10000;
MySqlDataReader rdrProduct = cmdProduct.ExecuteReader();
AutoCompleteStringCollection myCollectionSales1 = new AutoCompleteStringCollection();
if (rdrProduct.HasRows == true)
{
while (rdrProduct.Read())
{
// myCollectionSales1.Add(rdrProduct[0].ToString());
listOnit.Add(rdrProduct[0].ToString());
}
rdrProduct.Close();
//textBox1.AutoCompleteCustomSource = myCollectionSales1;
comboBox1.Items.AddRange(listOnit.ToArray());
}
I want the combobox to only display results that contain the whole string that has been typed in, not every phrase that has typed letters in any position as it seems like that's what it is doing.
I have tried to include the BeginIvoke method (not sure if done correctly thought as I have never used it before)
this.BeginInvoke((MethodInvoker)delegate
{
comboBox1.Items.Clear();
listNew.Clear();
var source = new AutoCompleteStringCollection();
foreach (var item in listOnit)
{
if (item.ToLower().Contains(this.comboBox1.Text.ToLower()))
{
listNew.Add(item);
}
}
comboBox1.Items.AddRange(listNew.ToArray());
comboBox1.SelectionStart = this.comboBox1.Text.Length;
Cursor = Cursors.Default;
comboBox1.DroppedDown = true;
});
Now when I start typing the first character, the combobox selects to top result right away (http://prntscr.com/pr5f6i). I have to press the first character again and then type the rest of the string to be able to actually search through the list.

Checkbox turning multiple values true

I've been stuck of this for a while and would love some insight.
When I add a new user or source and check the drawn checkbox, it causes the bool to be true when checked, as expected.
However it also checks all the other users connected to that source as true or false.
[before]
[after]
This only occurs when I load the XML file into my program that already had existing data, then add new Users or Sources via the UI.
this is a part of the LoadXML Method.
// Load the source list
sourceProps.SystemSources.Clear();
fCMUserSourceBindingSource.Clear();
fCMSourceBindingSource.Clear();
foreach (FusionSource src in fusionSystem.sourceList)
{
FCMSource fSource = new FCMSource(src);
sourceProps.SystemSources.Add(fSource);
fCMSourceBindingSource.Add(fSource);
fCMUserSourceBindingSource.Add(fSource);
}
txtSourceID.Text = sourceProps.GenerateNextSourceId();
// Load the user data from the fusionSystem object.
userProfile.SystemUserList.Clear();
//currently clears grid. might need to clear list instead
fCMUserBindingSource.Clear();
foreach (FusionUser usr in fusionSystem.userList)
{
FCMUser fUser = new FCMUser(usr);
userProfile.SystemUserList.Add(fUser);
fCMUserBindingSource.Add(fUser);
foreach (FusionSourcePermission srcPerm in usr.SourcePermissionList)
{
FCMSource fSource = new FCMSource(srcPerm);
fUser.fusionUserSources.Add(fSource);
}
}
AddColumnsUsersToSourceAllocation();
txtUserID.Text = userProfile.GenerateNextUserId();
// Load the zone group data from the fusionSystem object
zoneProps.systemZoneGroupList.Clear();
fCMZoneGroupBindingSource.Clear();
Any help would be appreciated.
Edit
The ListView is not binded and all the 'checking' is done programmatically when the user activates the click event.
private void lstSourceToUser_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if (e.ColumnIndex > 1)
{
int usrIndex = userProfile.GetUserIndexByID(e.Header.Name);
int srcIndex = userProfile.GetUsersSourceIndex(e.Header.Name, e.Item.SubItems[0].Text);
Graphics g = e.Graphics;
CheckBoxRenderer.DrawCheckBox(g,new Point((e.Bounds.X + e.Bounds.Width/2 -10 ),(e.Bounds.Y)), userProfile.SystemUserList[usrIndex].fusionUserSources[srcIndex].UserSourceChkBox.MyCheckedState ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal);
}
else
// Draw the other subitems with default drawing.
e.DrawDefault = true;
}
Edit
This is the FCMSource constructor.
public FCMSource(string sourceId, string sourceName, string icnId, string lstIndx)
{
id = sourceId;
icon = icnId;
name = sourceName;
listIndex = lstIndx;
UserSourceCheckState = false;
UserSourceChkBox = new MyCheckBoxItem(false);
}
public FCMSource(FCMSource fSource, bool chk)
{
name = fSource.name;
icon = fSource.icon;
id = fSource.id;
listIndex = fSource.listIndex;
UserSourceCheckState = chk ? true : false;
UserSourceChkBox = new MyCheckBoxItem(chk);
}
And this is the FCMUser constructor which contains the different Sources.
public FCMUser(string userid, string nm, string icn, string pinNo, CheckBox pinEn, string lstIndx)
{
id = userid;
name = nm;
icon = icn;
pin = pinNo;
pinEnabled = pinEn.CheckState;
chkBoxPINEnable = new MyCheckBoxItem(false);
fusionUserSources = new List<FCMSource>();
ListIndex = lstIndx;
updateCheckbox();
}

Combobox 'OnSelectedIndexChanged' not firing for certain values

I have a asp combo box inside update panel with autopost back set to true.
On page Load I fill combo box as
public DataTable getProductDetails()
{
MasterAllocationDB dataHandler = new MasterAllocationDB();
DataTable dataBoxType = null;
DataRow row = null;
try
{
dataBoxType = dataHandler.GetBoxType();
if (dataBoxType != null && dataBoxType.Rows.Count > 0)
{
row = dataBoxType.NewRow();
row["Product"] = "--Select--";
dataBoxType.Rows.InsertAt(row,0);
row = dataBoxType.NewRow();
row["Product"] = "Other";
dataBoxType.Rows.InsertAt(row, dataBoxType.Rows.Count);
}
}
catch (Exception ex)
{
LogHandler.LogMessageToFile(ex, LogMode.Fatal);
}
return dataBoxType;
}
Also I have a onselectedindexchanged event binded
protected void productComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string json = null;
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
var s = this.productComboBox.SelectedValue;
try
{
int totalNoOfItems = this.productComboBox.Items.Count;
// Make sure that Index are between "select a value" and "Other"
if (this.productComboBox.SelectedIndex > 0 && this.productComboBox.SelectedIndex < totalNoOfItems - 1)
{
//code here
}
json = new JavaScriptSerializer().Serialize(rows);
}
catch (Exception ex)
{
LogHandler.LogMessageToFile(ex, LogMode.Fatal);
}
}
As you can see I have added 2 extra rows besides the rows fetched from DB.The data rows are binding properly as I can see the same in outputed combo box values
After running I noticed that whenever I select "other" the text inside combo box gets changed
to "--select--" and control never reaches onselectedindexchanged
It works finely for all the other cases. What could be the reason?
Ok I sorted it out.
The problem is that I have only set text for the combo box not value for options.
Changed the code as
row["Product"] = "--Select--";
row["ProductID"] = "0";
row["Product"] = "Other";
row["ProductID"] = "10";
ProductId gives the value for combobox.
Happy coding

dropdownlist selected value is not changing?

dropdownlist selected value is not changing. although the string _month also contain the value but dropdownlist is not getting it.all other are working fine but only ddlMonth.selected value is not changing.i have assigned _month value to it but its not changing why? only ddlMonth is not changing all other are working fine why ddlmonth is not changing?
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue = _Month;
///here ddlMonth.selected value is not getting new value from _month
}
Other code is below
protected void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack)
return;
try
{
OnLoad();
GetYears();
if (!string.IsNullOrEmpty(ddlYear.SelectedValue))
hYearId.Value = ddlYear.SelectedValue;
GetPeriods(Convert.ToInt32(hYearId.Value));
GetDepartment();
GetSection();
#region Get Selected login user department and section
ddldepartment.SelectedValue = CommonMethods.UserContext.EmployeeDeparmentID;
ddlSection.SelectedValue = CommonMethods.UserContext.EmployeeSectionID;
#endregion
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
string name = Request.QueryString["id"] as string;
#region Create Cache object
ICacheManager _objYear = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objMonth = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objDepartment = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objSection = CacheFactory.GetCacheManager();//Create cache object
#endregion
if (Request.QueryString["ClickTag"]!=null)
{
#region set Cached items
if (Request.QueryString["ClickTag"].ToString() == "1")
{
if (_objYear.Contains("Year"))
{
string _Year = (string)_objYear.GetData("Year");
ddlYear.SelectedValue = _Year;
}
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue= _Month;
}
if (_objDepartment.Contains("Department"))
{
string _Department = (string)_objDepartment.GetData("Department");
ddldepartment.SelectedValue= _Department;
}
if (_objSection.Contains("Section"))
{
string _Section = (string)_objSection.GetData("Section");
ddlSection.SelectedValue = _Section;
}
}
#endregion
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(ddlMonth.SelectedValue))
{
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
if (ddlSection.SelectedIndex > 0)
ddlSection_SelectedIndexChanged(null, null);
}
}
void GetPeriods(int _year)
{
IBLCalenderPeriod _bl = (IBLCalenderPeriod)SetupBLFactory.GetCalenderPeriod();
DataSet _ds = (DataSet)_bl.GetPeriodIdsByYear(_year).GetMaster();
_ds.Tables[0].Columns.Add("ID");
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
_dr["ID"] = _dr["CLP_ID"] + "," + _dr["clp_activeperiod"] + "," + _dr["CLP_DATESTART"] + "," + _dr["CLP_DATEEND"] + "";
}
ddlMonth.DataSource = _ds.Tables[0];
ddlMonth.DataTextField = "CLP_DESCRIPTION";
ddlMonth.DataValueField = "ID";
ddlMonth.DataBind();
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
if (_dr["clp_activeperiod"] != null)
if (_dr["clp_activeperiod"].ToString() == "1")
{
ddlMonth.SelectedValue = _dr["ID"].ToString();
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
break;
}
else
{
ddlMonth.SelectedIndex = 0;
hClpid.Value = "0";
}
}
}
I think you are setting a value in ddlMonth but ddlMonth do not have that binded value.. Try to bind list of values in your ddlMonth before setting a value to it
Please next time format the code before posting.
For the problem I think the solution is to put the region where you set the SelectedValue inside an
if(!isPostback){...}
I suggest you to take a look to the documentation about page lifecycle, because the explanation is that the Page_Load in executed not only the first time you load a page, but also for every postback (if you don't use the if(!isPostback){...}

Combobox - setting datasource clears Items

I have a routine that populates a combobox from a database; the first time the combo is populated, it all works perfectly, but if I try to do it again, the combobox is completely blank. I narrowed it down to this line:
cboThis.DataSource = cboThis.Items;
This seems to clear the Items collection for the combobox...but only if the combo was already populated.
Any ideas what could be going on here?
There IS an event handler for one of the combo's SelectedIndexChanged event, but this doesn't seem to get called by anything but the first and last lines of code.
Here's the complete routine:
public void ComboFromDB(ComboBox cboThis, string strTable, string strField)
{
cboThis.SelectedIndex = -1;
cboThis.DataSource = null;
cboThis.Items.Clear();
string strQuery = #"SELECT ID, " + strField + " FROM " + strTable;
using (SqlConnection sqcConnection = new SqlConnection(strConnection))
{
sqcConnection.Open();
SqlCommand sqcCommand = new SqlCommand(strQuery, sqcConnection);
SqlDataReader dr = sqcCommand.ExecuteReader();
while (dr.Read())
{
cboThis.Items.Add(new ComboItem((int)dr[0], dr[1].ToString())); //this all works fine
}
}
cboThis.DataSource = cboThis.Items; //This line clears cboThis.Items...
cboThis.ValueMember = "ID";
cboThis.DisplayMember = "Display";
cboThis.SelectedIndex = -1;
}
Cheers
try to create a structure like this
struct tmpItems
{
//member variables
private Int32 _ID;
private String _Display;
//properties
public Int32 ID
{
get {return _ID;}
}
public String Display
{
get {return _Display;}
}
public tmpItems(Int32 pID , String pDisplay)
{
_ID = pID;
_Display = pDisplay;
}
}
now assign
ArrayList dataItems = new ArrayList();
dataItems.Add(new tmpItems((int)dr[0], dr[1].ToString()));
then finally set
cbothis.DataSource = dataItems;
cboThis.ValueMember = "ID";
cboThis.DisplayMember = "Display";
Ensure that ComboBox SelectedIndexChange event handles the Initialization of data..
because while setting datasource , the items will be added one by one.. each time generating SelectedIndexChangeEvent .. but will find difficult in accessing SelectedValue property at this stage
In the end I binned using Items and just shoved it through a Dictionary.

Categories