从对象类型System.Web.UI.WebControls.DropDownList到已知的托管提供程序本机类型没有映射

时间:2018-10-19 15:14:27

标签: c# asp.net

我正在尝试将GridView值存储到数据库中,但是我不断收到错误消息:

  

不存在从对象类型System.Web.UI.WebControls.DropDownList到已知的托管提供程序本机类型的映射。

界面:“出勤”列是我插入到网格视图中的模板

X

下面是我的代码c#:

for (int i = 0; i < GVAttend.Rows.Count; i++) {
    SqlConnection Con = new SqlConnection();
    Con.ConnectionString = "Data Source=(local);Initial Catalog=Data;Integrated Security=True";

    String query2 = "Insert into Attendance(Student_ID, Course_Code, Date, Status, Student_Name, Att_by) Values(@Stu_ID ,@Course_Code ,@Date ,@Status ,@Stu_Name ,@Attby)";
    SqlCommand Cmd = new SqlCommand(query2, Con);

    Cmd.Parameters.AddWithValue("@Stu_ID", GVAttend.Rows[i].Cells[0].ToString());
    Cmd.Parameters.AddWithValue("@Course_Code", DropCourse.SelectedItem.Text);
    Cmd.Parameters.AddWithValue("@Date", Calendar1.SelectedDate.Date.GetDateTimeFormats()[8].ToString());
    Cmd.Parameters.AddWithValue("@Stu_Name", GVAttend.Rows[i].Cells[1].ToString());
    Cmd.Parameters.AddWithValue("@Status", GVAttend.Rows[i].Cells[2].FindControl("DropAtt") as DropDownList);
    Cmd.Parameters.AddWithValue("@Attby", Session["Username"].ToString());

    Con.Open();
    Cmd.ExecuteNonQuery();

    Con.Close();
}

2 个答案:

答案 0 :(得分:1)

   Cmd.Parameters.AddWithValue("@Status", GVAttend.Rows[i].Cells[2].FindControl("DropAtt") as DropDownList); 

看起来很腥

您应该从下拉列表中获得选定的值

 Cmd.Parameters.AddWithValue("@Status", (GVAttend.Rows[i].Cells[2].FindControl("DropAtt") as DropDownList).SelectedItem.Value)

答案 1 :(得分:1)

通过列索引搜索控件非常脆弱。如果您不小心移动了列,它将抛出运行时异常。

foreach (GridViewRow row in GVAttend.Rows)
{
    ...
    var dropAtt = row.FindControl("DropAtt") as DropDownList;
    Cmd.Parameters.AddWithValue("@Status", dropAtt.SelectedValue);    
    ...
}