我想問你是否可以幫助我使用我的代碼,因爲我沒有得到我想要的結果,即加載某個特定的細節紙張從下拉列表中。當從下拉列表中選擇一個項目時數據不會更新
當前,頁面加載時,所選項目的詳細信息將加載。但是,當我嘗試從下拉列表中選擇另一個項目時,相應的細節將不會顯示出來,而前一個仍然保留。
在下拉列表的屬性下,我還將autopostback設置爲yes,以便它會自動加載所選項目的相應詳細信息。
請參考下面
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
代碼期待您的反饋意見在這裏。謝謝!
調試程序,你會很容易抓住問題:) –
什麼是你的DropDownList默認了selectedValue? – Izikon
默認值是1(PaperID),它對應於該產品ID的紙張名稱。 –