访问数据集 - "cannot find table 0"

Accessing a dataset - "cannot find table 0"

我在表单上有一个获取数据集的方法,我试图调用它来填充组合框,但未找到 table。我错过了什么?

这是数据集方法...

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

这里是我尝试调用方法的地方...

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);
    }
}

非常感谢任何帮助!

您尝试在数据集被填充之前访问 table。新数据集将不包含任何 tables.

您必须在填充数据集后访问 table 0,因为当您创建新数据集时,它没有 tables。

例如

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();

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

    maxRows = dsAddWO.Tables[0].Rows.Count;

    //Return the dataset
    return dsAddWO;
}

希望对您有所帮助

再见