簡體   English   中英

如何將信息從數據庫加載到 Asp.Net 中的標簽?

[英]How to load information from database to a Label in Asp.Net?

當用戶單擊上一頁中的鏈接按鈕時,我想從數據庫中的特定列加載數據。

我正在使用SqlDataReader來執行此操作,但出現錯誤:

指數數組的邊界之外。

這是我的代碼:

private void loadDetails()
{
    if (con.State == ConnectionState.Closed)
        con.Open();
    SqlCommand cmd = new SqlCommand("select expectation from Tours where tourName ='" + tournameLb.Text + "'", con);
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("@expectation", lb5.Text);

    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        lb5.Text = dr[4].ToString(); //I get error here 
    }
    dr.Close();
    con.Close();
}

在哪里

tournameLb.Text = Session["tourName"].ToString();

您正在使用該值的參數,這是一個好方法,但您需要使用參數化查詢:

SqlCommand cmd = new SqlCommand("select expectation from Tours where tourName = @expectation", con);

此外,您的查詢只會返回一列,但您正在嘗試獲取不存在的第五列的值:

lb5.Text = dr[0].ToString();

或者,您可以使用列名而不是索引:

lb5.Text = dr["expectation"].ToString();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM