Search code examples
c#sqlclient

Accessing a dataset - "cannot find table 0"


I have a method on a form for getting a dataset, which i'm trying to call to populate a combobox but the table is not being found. What am I missing?

Here's the dataset method...

public partial class frmForm2 : Form
{
    #region Variables

    //Connection string
    string conString = ("Data Source=L008##\\#####; Initial Catalog=FiT; Integrated Security=SSPI;");

    //Data Variables
    int maxRows;
    int userID = frmForm1.user_ID;

    #endregion

    #region SQL Conn & Dataset

    public DataSet GetDataSet(string connectionString)
    {
        //Create connection object
        SqlConnection sqlCon = new SqlConnection(connectionString);
        SqlDataAdapter daAddWO = new SqlDataAdapter();
        SqlCommand cmd = sqlCon.CreateCommand();
        cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=@userID");

        //Initialise the parameter
        cmd.Parameters.AddWithValue("@userID", userID);

        //Pass the SQL query to the da
        daAddWO.SelectCommand = cmd;

        //Create the dataset
        DataSet dsAddWO = new DataSet();
        maxRows = dsAddWO.Tables[0].Rows.Count;

        //Open the connection and fill the dataset
        sqlCon.Open();
        daAddWO.Fill(dsAddWO);
        sqlCon.Close();

        //Return the dataset
        return dsAddWO;
    }
    #endregion

And here's where I'm trying to call the method...

public frmForm2()
{
    InitializeComponent();

    try
    {
        //Request dataset 
        DataSet dsAddWO = GetDataSet(conString);
        DataRow dRow;
        int incRow = 0;
        dRow = dsAddWO.Tables[0].Rows[incRow];

        comboBox1.Text = dRow.ItemArray.GetValue(1).ToString();
    }
    catch (Exception err)
    {
        MessageBox.Show(err.Message);
    }
}

Any help much appreciated!


Solution

  • You try to access the table before the dataset has been filled. A new dataset will not contain any tables.