473,715 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataBinding a ListBox's SelectedValue to integer field from DataSet gives error

Hello everyone,

I know this question has been asked many times in the forums, and after
spending a few days reading, I am still confused as to the answer.

I have a ListBox (lstBox), SqlConnection (sqlConnection) ,
SqlDataAdapter (daLookupData), SqlDataAdapter (daData), DataSet
(dsLookupData), and DataSet (dsData), all created via the IDE during
design-time. Here is the design of my simple tables: (An example
since I can't post my real tables, etc.)

LookupDataTable
----------------
LookupDataID - int (identity)
LookupDataText - nvarchar(25)

Data
-----
LookupDataID - int
(Other nvarchar textbox nullable fields)
Each DataAdapter has a command that simply selects * from each table,
respectively.

Here are the properties I've edited for lstBox:

DataMember: LookupDataTable (An existing table)
DataSource: dsLookupData
DataTextField: LookupDataText (nvarchar(25))
DataValueField: LookupDataID (int)

I then went to DataBindings and changed the SelectedValue to be:

DataBinder.Eval (dsData, "Tables[Data].DefaultView.[0].LookupDataID",
"{0:N}")

Here is my Page_Load:

//----------------------------------------------
sqlConnection.O pen();
if (!Page.IsPostBa ck)
{
daLookupData.Fi ll(dsLookupData );
daData.Fill(dsD ata);
Page.DataBind() ;
}
sqlConnection.C lose();
//----------------------------------------------

Since there is no data in the Data table, a null value is returned to
the lstBox's SelectedValue. Since that value doesn't exist, the web
application bombs stating:

"Specified argument was out of the range of valid values. Parameter
name: value "

and it's pointing to the Page.DataBind() as the error line;

I know it is the SelectedValue because when I unbind that property, it
all works as intended. I have also attempted changing to the ISNULL
T-SQL recommended on some posts, but there is no -1 or 0 value, so it
still bombs. I am unable to have an extra entry in the listbox--only
those values currently in the LookupDataTable can be shown in the list.

I know there exists a problem where null values are causing web
applications to crash like this, and I have read many ways to fix it,
but none seem to work. I still would like to use databinding to
accomplish the loading of the data into these controls and the setting
of values for each record, but would not mind overloading a function or
creating an event handler for this, but do not know what ones would be
needed. I've also seen code where you check for null to set it to
DBNull.value or an empty string, but where exactly does that code go in
this situation? I have seend DataBinding classes that do not exist in
the web forms, only in Windows forms, so that is out of the question
(unless I'm mistaken).

Basically, if a null value exists, I need nothing to be selected, and
if one does, then I need that one to be selected.

I since added a button to check the current value of this box unbound,
and it seems to be an empty string (''), however, when I try to
ISNULL(...) to a nvarchar empty string, it does not work (yes, I did
change the type in the xsd file).

Has anyone found a solution for this problem while still using
databinding for the datasource AND selectedvalue, and if
events/overloaded functions were used to accomplish this, what ones
should I research? My thought was if I could overload the function
that sets the value at the time of databinding, so I could trap the
error, I could just not set the selected value and continue on,
allowing the next databind to get the value if the next one existed.
Thank you all in advance.

David

Nov 19 '05 #1
4 4208
David,
I think your problem is that you have fundamentally overcomplicated things.
The reason you are probably confused by the answers you've received is
likely because the people trying to help you have been confused by the
question asked - god knows I am.

I'm not trying to put you down and am willing to work with you to find a
solution, but I think it's important you know that it seems that you are
either overcomplicatin g your code or that you aren't properly explaining it.

Let me rephrase your question as I understand it, simplified, so that you
might tell me if I'm right or wrong.

(a) you are binding a dataset to a listbox
(b) you are trying to set the selectedValue
Now, it seems to me that your page_load should look like this:

Page_Load
if (!Page.IsPostBa ck){
dsLookupDate = GetYourDataFrom SomeFunction()
lstBox.DataSour ce = dsLookupData
lstBox.DataMemb er = "LookupDataTabl e"
lstBox.DataText Field = "LookupDataText "
lstBox.DataValu eField = "LookupData Id"
lstBox.DataBind ()
//set the selected value here
}

now, notice that I couldn't have solved your problem because I didn't set
your selected value, which you think is the problem. The reason I didn't is
because I don't understand what the heck you want as the selected value. I
don' t understand what you hope/want this to do: DataBinder.Eval (dsData,
"Tables[Data].DefaultView.[0].LookupDataID", "{0:N}")

I understand that you are binding to LookupDataTable and you want the
selectedValue to be based on something in the Data table, but I don't
understand which LookupDataId you wish to have? The first one in the Data
table? Is your problem when the entire data table has no rows?

Please clarify for me.

Karl

--
MY ASP.Net tutorials
http://www.openmymind.net/
<dt***********@ gmail.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
Hello everyone,

I know this question has been asked many times in the forums, and after
spending a few days reading, I am still confused as to the answer.

I have a ListBox (lstBox), SqlConnection (sqlConnection) ,
SqlDataAdapter (daLookupData), SqlDataAdapter (daData), DataSet
(dsLookupData), and DataSet (dsData), all created via the IDE during
design-time. Here is the design of my simple tables: (An example
since I can't post my real tables, etc.)

LookupDataTable
----------------
LookupDataID - int (identity)
LookupDataText - nvarchar(25)

Data
-----
LookupDataID - int
(Other nvarchar textbox nullable fields)
Each DataAdapter has a command that simply selects * from each table,
respectively.

Here are the properties I've edited for lstBox:

DataMember: LookupDataTable (An existing table)
DataSource: dsLookupData
DataTextField: LookupDataText (nvarchar(25))
DataValueField: LookupDataID (int)

I then went to DataBindings and changed the SelectedValue to be:

DataBinder.Eval (dsData, "Tables[Data].DefaultView.[0].LookupDataID",
"{0:N}")

Here is my Page_Load:

//----------------------------------------------
sqlConnection.O pen();
if (!Page.IsPostBa ck)
{
daLookupData.Fi ll(dsLookupData );
daData.Fill(dsD ata);
Page.DataBind() ;
}
sqlConnection.C lose();
//----------------------------------------------

Since there is no data in the Data table, a null value is returned to
the lstBox's SelectedValue. Since that value doesn't exist, the web
application bombs stating:

"Specified argument was out of the range of valid values. Parameter
name: value "

and it's pointing to the Page.DataBind() as the error line;

I know it is the SelectedValue because when I unbind that property, it
all works as intended. I have also attempted changing to the ISNULL
T-SQL recommended on some posts, but there is no -1 or 0 value, so it
still bombs. I am unable to have an extra entry in the listbox--only
those values currently in the LookupDataTable can be shown in the list.

I know there exists a problem where null values are causing web
applications to crash like this, and I have read many ways to fix it,
but none seem to work. I still would like to use databinding to
accomplish the loading of the data into these controls and the setting
of values for each record, but would not mind overloading a function or
creating an event handler for this, but do not know what ones would be
needed. I've also seen code where you check for null to set it to
DBNull.value or an empty string, but where exactly does that code go in
this situation? I have seend DataBinding classes that do not exist in
the web forms, only in Windows forms, so that is out of the question
(unless I'm mistaken).

Basically, if a null value exists, I need nothing to be selected, and
if one does, then I need that one to be selected.

I since added a button to check the current value of this box unbound,
and it seems to be an empty string (''), however, when I try to
ISNULL(...) to a nvarchar empty string, it does not work (yes, I did
change the type in the xsd file).

Has anyone found a solution for this problem while still using
databinding for the datasource AND selectedvalue, and if
events/overloaded functions were used to accomplish this, what ones
should I research? My thought was if I could overload the function
that sets the value at the time of databinding, so I could trap the
error, I could just not set the selected value and continue on,
allowing the next databind to get the value if the next one existed.
Thank you all in advance.

David

Nov 19 '05 #2
Hi Karl,

Yes, you are on the right track. I didn't set up the lstBox properties
in code--I did them during design-time using the properties given in
the IDE, which is why there's no need for them to be in the Page_Load.

I was under the impression that you could eliminate the function to get
the dataset since you can have the DataAdapter fill the dataset with
the data as outlined in your command object, which is why I thought
there was no need for a function to return a dataset--again, the
dataset was already generated by the IDE from the DataAdapter.

In my example, I have a lookup table and another table with an ID
corresponding to an item in that lookup table. This is an optional
field and the value could be null, which is where I am having my
problem. If it is null, that's where I get my error in the
SelectedValue. As for what I'm getting, it shouldn't matter--whether
it's the first, last, middle, or even if there is no data, if that ID
field has returned a null value, it crashes.

Thanks for helping. :)

Nov 19 '05 #3
Dan,
My fictitious function to get the dataset would basically just does what you
did (use the dataAdapter to fill the dataset and return it). The benefit of
the function is that it could be reused more easily in some other part of
the code...say another page which wanted to bind to it....that's symatics
though and I was just trying to establish flow. Same with those other
properties, I figured you were doing it at design time but for illustration
purposes I much rather do it in codebehind so that nothing is assumed (well,
in real world I rather do it there too, but again, symatics).

Still not 100% clear however....I'm understanding that Data only has 1
record (possibly none, or posibly a record with a null Id) or that we are
only interested in the first record.

doesn't something like:

int id;
if (dsLookupData.T ables["Data"].Rows[0]["LookupData Id"] != DbNull.Value){
lstBox.Selected Index =
lstBox.Items.In dexOf(lstBox.It ems.FindByValue (dsLookupData.T ables["Data"].Ro
ws[0]["LookupData Id"].ToString))
}

work? might have a couple errors in there, but the general idea I'd expect
to work...

This is probably something you can't easily do in design time...even with
databinding expressions (Which I'm thinking might be where you are going
wrong).

Karl
--
MY ASP.Net tutorials
http://www.openmymind.net/
"dblanken" <dt***********@ gmail.com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .
Hi Karl,

Yes, you are on the right track. I didn't set up the lstBox properties
in code--I did them during design-time using the properties given in
the IDE, which is why there's no need for them to be in the Page_Load.

I was under the impression that you could eliminate the function to get
the dataset since you can have the DataAdapter fill the dataset with
the data as outlined in your command object, which is why I thought
there was no need for a function to return a dataset--again, the
dataset was already generated by the IDE from the DataAdapter.

In my example, I have a lookup table and another table with an ID
corresponding to an item in that lookup table. This is an optional
field and the value could be null, which is where I am having my
problem. If it is null, that's where I get my error in the
SelectedValue. As for what I'm getting, it shouldn't matter--whether
it's the first, last, middle, or even if there is no data, if that ID
field has returned a null value, it crashes.

Thanks for helping. :)

Nov 19 '05 #4
I think I got it. It was a problem with the databinding expression. I
found that you can set it to anything, even a function, as long as it
returns a null or string to the SelectedValue. So I made a function
that is as follows:

public string SelectVal(DataS et ds, string strField)
{
if (ds.Tables[0].Rows[0][strField] != DBNull.Value)
return (ds.Tables[0].Rows[0][strField]).ToString();
return null;
}

Then, my databinding expression for SelectedValue is: SelectVal(dsDat a,
"LookupTableID" )

If it returns null, then nothing is selected, just as it should be; and
if there is a value, it will select it.

Thanks for your help!

Nov 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2020
by: Supa Hoopsa | last post by:
Working on a windows form, I am trying to bind a listbox to a dataset and want to set the displaymember & Valuemember properties of the listbox so that I can retrieve the selectedvalue from a selecteditem in the listbox. My code is very simple: lstReports.DataBindings.Clear() lstReports.DataSource = dsDataSet.Tables("Reports") lstReports.DisplayMember = "ReportDescription" lstReports.ValueMember = "ReportsKey"
2
1966
by: Alpha | last post by:
I have a window application. On one of the form, there is a listbox and a few combox. The lstSchItem has a dataview as a datasource. The comboxes are bind to its selected value but through the dataset table. Now when I change the selection in the lstSchItem the comboxes are staying the same and not reflecting the changes. I tried changing the binding to the dataview.table but the comboxes are still not changing to reflect the...
4
2458
by: Moe Sizlak | last post by:
Hi There, I am trying to return the value of a listbox control that is included as a user control, I can return the name of the control but I can't access the integer value of the selected item, what do I need to do in order to return the "option value" of the control? Moe !--- returned value of the control
3
5740
by: Big E | last post by:
I'm using ASP.Net and SQL Server. I have a listbox looks up data from a table and fills the listbox. I have a stored procedure that looks up the selected values and tries to show them as selected in the listbox. My FOR NEXT LOOP gets stuck on one record in the datatable. There are 4 records in the datatable and only the first one is selected. It never moves past the first record. MyCommand.Fill(dsCom, "tblCommRealtorAssociation") ...
4
1324
by: JV | last post by:
It's easy to databind a listbox or dropdownlist if all you want is to fill it with a list of values. There are plenty of examples in the online help. Unfortunately, real world applications demand more. Usually you would also like to bind the SelectedValue to something else. Common scenario: You have an ADDRESS table with a foreign key to a STATE table. You join on an integer or uniqueidentifier key value, but the STATE table is what...
6
2231
by: Young J. Putt | last post by:
I've got a list box bound to a Datatable, like this: lstProjects.DataSource = m_oProjectSet.DataTable lstProjects.DisplayMember = "ProjectDesc" lstProjects.ValueMember = "ProjectID" I want to pass the ProjectID value (integer) of the selected item in lstProjects to another function. I assumed I could reference the integer value of the ProjectID column as
1
3621
by: Gary Shell | last post by:
I have a pair of combo boxes on a form. Both have their SelectedValue property bound to a column on a table called "Input_Output". One column is called "Class" and the second is called "SubClass". Each combobox has its datasource, displaymember and SelectedValue member bound to separate tables thru individual datatsets thru individual data adapters. The two tables are "Class" and "SubClass". I use parameterized query to populate the...
1
1388
by: amar shukla | last post by:
hi all, i have a problem, i am coding a problem, which is suppose to fetch records from database into a combobox and there after based on the selection of value it has to proceed further , i have used sqldataadpter.fill(dataset) as well for the selectedvalue,
1
3468
by: Mundo | last post by:
Hi I'm pulling my hair out with a problem caused when DataBinding a DataSet to a web control. I first tried using a GridView but when that failed, I tried a Repeater. I'm getting the classic "'System.Data.DataRowView' does not contain a property with the name X" error message which suggests I'm not putting X in the SELECT statement. But this is not the case. If I set the GridView to AutoGenerateColumns="true", it works fine and all the...
0
8821
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8718
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9196
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9047
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6646
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5967
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4477
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4738
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3175
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.