访问datalist中的控件

时间:2012-01-01 06:46:00

标签: c# asp.net visual-studio-2010 datalist

我正在创建一个带有RadioButtonList的数据列表作为数据列表中显示的每个帖子的评级量表,但是当我评价一个帖子时,所有其他帖子评分相同,你能告诉我问题出在哪里,谢谢。 PS:我知道问题出在foreach循环中,如果我删除它,我将无法访问RadioButtonList或postIDLabel

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e) {
  foreach (DataListItem item in DataList2.Items) {
    RadioButtonList RadioButtonList1=(RadioButtonList)item.FindControl("RadioButtonList1");
    string choice = RadioButtonList1.SelectedValue;

    Label post_IDLabel = (Label)item.FindControl("post_IDLabel");
    int post_ID = Convert.ToInt32(post_IDLabel.Text);
    int value = Convert.ToInt32(choice);

    string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
    SqlConnection conn = new SqlConnection(connStr);

    SqlCommand cmd = new SqlCommand("rate", conn);
    cmd.CommandType = CommandType.StoredProcedure;
    string email = Session["email"].ToString();
    int course_ID = Convert.ToInt32(Request.QueryString["courseID"]);
    cmd.Parameters.Add(new SqlParameter("@course_ID", course_ID));
    cmd.Parameters.Add(new SqlParameter("@postID", post_ID));
    cmd.Parameters.Add(new SqlParameter("@myemail", email));
    cmd.Parameters.Add(new SqlParameter("@rate", value));

    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();

    Response.Write(choice);
  }
  DataList2.DataBind();
}

1 个答案:

答案 0 :(得分:2)

使用NamingContainer获取DataListItem。

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
 RadioButtonList rad = sender as RadioButtonList;
 DataListItem item = rad.NamingContainer as DataListItem;
 Label lab = item.FindControl("postIDLabel") as Label ;
 Response.Write(lab.Text);
}