請問如果同時SELECT到的資料要分筆輸出的話可行嗎?就是要把搜尋到的三筆資料分別輸出在不同的LABEL。
如果打成下面那樣的話兩個LABEL會顯示同筆資料
Label1.Text = dr["ID"].ToString();
Label2.Text = dr["ID"].ToString();
下面是我用C#寫的程式~~謝謝^^
SqlConnection Conn = new SqlConnection("server=localhost\\SQLEXPRESS; database=mytest; uid=sa; pwd=ra123!@#");
Conn.Open(); //連結資料庫
SqlCommand cmd = new SqlCommand("select top 3 * from ite order by newid()", Conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Label3.Text = Label3.Text + "
" + dr["ID"].ToString();
}
cmd.Cancel();
dr.Close();
Conn.Close();
--------------------------------------------------------------------------------
我會建議你用用List<T>,也就是List<Label>
List<Label> _List = new List<Label>();
//下面這行可以改成Add你已經產生的Label
for(Int32 a = 0; a != 3; a += 1) { _List.Add(new Label()); }
SqlConnection Conn = new SqlConnection("server=localhost\\SQLEXPRESS; database=mytest; uid=sa; pwd=ra123!@#");
Conn.Open();
SqlCommand cmd = new SqlCommand("select top 3 * from ite order by newid()", Conn);
SqlDataReader dr = cmd.ExecuteReader();
//接著下面
for(Int32 a = 0; a != 3; a += 1)
{
dr.Read();
_List[a].Text = Convert.ToString(dr["ID"]);
}
//其實這裡如果改用using, 可以偷懶不用自己呼叫Dispose, 不過還是看你整個程式流程來決定
//如果後續還要繼續用, connection可以先別Dispose, reader可Close後設為null, cmd可設為null
dr.Dispose();
cmd.Dispose();
Conn.Dispose();
//玩完之後, 最後請記得將List清空, 移除他的對應
_List.Clear();
內文搜尋

X