我在表单上有一个获取数据集的方法,我试图调用它来填充组合框但是找不到表。我错过了什么?
这是数据集方法......
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);
}
}
非常感谢任何帮助!
答案 0 :(得分:1)
填充数据集后,您必须访问表0,因为当您创建新数据集时,它没有表格。
e.g。
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;
}
希望有所帮助
再见
答案 1 :(得分:0)
您尝试在填充数据集之前访问该表。新数据集不包含任何表格。