仍在學習C#表單被加載,但如何從SQL中提取數據到組合框?
創建一個組合框,並創建一個名爲mainCat和SUBCAT表。
我有一個代碼,但我堅持瞭解如何將數據從mainCat獲取到組合框,然後由另一個組合框用於子控件設置子類別。
的獲取連接的紅色下劃線。爲什麼?
這裏是我的代碼 -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
所以我然後我嘗試另一個代碼..但還是不工作..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
然後我就通過下拉框使用數據綁定項功能GUI ..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
但是,該框沒有顯示任何值,除了「System.Data.DataRowView」在comboBo中X
============================================= =====================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
====== =========
和組合框仍然沒有顯示從數據庫表
智能感知應該告訴你爲什麼,但在猜測,沒有'的getConnection()'存在嗎?如果是的話,請張貼它的代碼 –
啊..不..我不認爲它存在..是代碼的方式是否正確? –
我相信它會編譯,如果你創建連接功能 –