Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting a record from listbox

Status
Not open for further replies.

prrm333

Programmer
Apr 14, 2003
97
US
I use the following to get a record from clicking on a row in a list box:

private void loadConn3(string sLName, string sFName)
{
m_dtContacts.Clear();
txtID.Text = "";
txtFirstName.Text = "";
txtLastName.Text = "";
txtStreet1.Text = "";
txtStreet2.Text = "";
txtState.Text = "";
m_cnADONetConnection.ConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=contacts.mdb";
m_cnADONetConnection.Open();
string sqlText = "Select * From Contacts where [LastName] = '" + @sLName + " and [FirstName] = " + @sFName + "'";
m_daDataAdapter =
new OleDbDataAdapter(sqlText, m_cnADONetConnection);

OleDbCommandBuilder m_cbCommandBuilder =
new OleDbCommandBuilder(m_daDataAdapter);
m_daDataAdapter.Fill(m_dtContacts);
//this.ShowCurrentRecord();
txtID.Text = m_dtContacts.Rows[m_rowPosition]["ID"].ToString();
txtLastName.Text = m_dtContacts.Rows[m_rowPosition]["LastName"].ToString();
txtFirstName.Text = m_dtContacts.Rows[m_rowPosition]["FirstName"].ToString();
txtStreet1.Text = m_dtContacts.Rows[m_rowPosition]["StreetAddress1"].ToString();
txtStreet2.Text = m_dtContacts.Rows[m_rowPosition]["StreetAddress2"].ToString();
txtState.Text = m_dtContacts.Rows[m_rowPosition]["State"].ToString();

m_cnADONetConnection.Close();
}

When I do so I get the following error:

There is no row at position 0. Stopping on the first textbox to fill above. It works okay for only a last name except that won't be okay for duplicate last names.

Any ideas?
Thanks.
 
just to give my thoughts about the error, it's probably coz the query returned zero records. When you tried to access Rows @ zero, you get the exception. You need to decide what to do if the lastname & firstname do not match any records.
 
If you're expecting only one record from the database for that contact, I suggest you bind the contact ID to the listbox and use that value instead of the names to query the database.

In any case how are your setting the m_rowPosition value? If you're only expecting one record as stated above, this value should be 0.
 
I have taken the suggestion and I am using the Contact ID instead. However, now I am trying to not show the Contact ID in the listbox but use it hidden behind the scene to query the database and get the record selected from the listbox.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top