【问题标题】:No mapping exists from object type System.Web.UI.WebControls.DropDownList to a known managed provider native type不存在从对象类型 System.Web.UI.WebControls.DropDownList 到已知托管提供程序本机类型的映射
【发布时间】:2018-10-19 15:14:27
【问题描述】:

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

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

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

下面是我的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();
}

【问题讨论】:

    标签: c# asp.net


    【解决方案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)
    

    【讨论】:

    • 感谢您的回复 Gaurav,我尝试了您的代码并收到此消息:字符串或二进制数据将被截断。声明已终止。
    • 它是您在 sqlserver 中的数据类型,这会导致问题。您在 sqlserver 中为 @Status 列使用的数据类型是什么。希望您使用的是 varchar。
    • @Status varchar(30)
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢 Win,我还没有尝试你的代码,因为“row”.FindControl 出现错误。有什么建议吗?
    • 上面的代码是在哪个事件中放置的?你能发布异常消息吗?
    • 代码在 protected void btnaddatt_Click(object sender, EventArgs e) { var DropAtt = row.FindControl("DropAtt") as DropDownList; Cmd.Parameters.AddWithValue("@Status", DropAtt.SelectedValue);它表示当前上下文中不存在名称“行”。
    • 您需要迭代GVAttend.Rows并获取GridViewRow对象。请看我的回答。
    • 感谢您指出这一点,我不敢相信我错过了。我仍然无法执行查询。收到此消息:“字符串或二进制数据将被截断。语句已终止”。有什么想法请...
    猜你喜欢
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多