在調用“Fill”前,SelectCommand 屬性尚未初始化
是因為少寫了一行代碼:
private readonly string strConnection = System.Configuration.ConfigurationManager.AppSettings["ConnStr"].ToString();
private void Form1_Load(object sender, EventArgs e) { string a = "2"; string sql = " select Date from T_BasicData where userid = '" + a + "'"; //DataTable DT = Classbase.pubfun.GetSercherGridSource(sql); DataTable DT = GetSercherGridSource(sql); string b = DT.Rows[0][0].ToString(); MessageBox.Show(b); }
public DataTable GetSercherGridSource(string cmdText) { DataTable DT = null; SqlConnection conn = new SqlConnection(strConnection); SqlCommand cmd=conn.CreateCommand(); SqlDataAdapter adp=new SqlDataAdapter(); adp.SelectCommand = cmd; DataSet ds =new DataSet(); cmd.CommandText=cmdText; adp = new SqlDataAdapter(); try { conn.Open() ; adp.SelectCommand = cmd;//看看有沒有這句代碼 adp.Fill(ds) ; if (ds != null) { DT = ds.Tables[0]; } return DT; } catch (Exception e) { //MessageBox.Show("錯誤"); //MessageBox.Show(string.Format("異常!以下為數據庫提示詳細錯誤信息:{0}{1}", Environment.NewLine, cct.CUR_ERROR), "提示"); MessageBox.Show(string.Format("異常!以下為數據庫提示詳細錯誤信息:{0}{1}", Environment.NewLine, e.Message), "提示"); //MessageBox.Show(e.Message); return DT; } }