-1

我正在尝试通过编码从详细信息视图将数据插入或更新到数据库中。无需为详细信息视图提供数据源,因为它非常简单。我想以编程方式进行。

正如我所说,我没有直接提供数据源。我在页面加载时做到了。

static string conn = ConfigurationManager.ConnectionStrings["AptechConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conn);

protected void Page_Load(object sender, EventArgs e)
{
    DetailsView1.AutoGenerateInsertButton = true;
    DetailsView1.AutoGenerateEditButton = true;
    DetailsView1.AutoGenerateDeleteButton = true;
    Data_Bind();
}

public void Data_Bind()
{
    string query = "select * from students";
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

    DetailsView1.DataSource = dt;
    DetailsView1.DataBind();
    ViewState["Data"] = dt;
}

我试着像我们在gridview中那样做

protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
    try
    {
        id = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox1");
        name = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox2");
        batch = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox3");
        enrolled = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox4");
        teacher = (TextBox)DetailsView1.Rows[0].Cells[1].FindControl("TextBox5");
    }
    catch (Exception ex)
    {
        Label1.Text = ex.Message;
        Label1.Visible = true;
    }
}

protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
    switch (e.CommandName.ToString())
    {
        case "New":
            DetailsView1.ChangeMode(DetailsViewMode.Insert);
            Data_Bind();
            break;
    }
}

但是,当我单击编辑或插入链接按钮时,它给了我这个错误

DetailsView 'DetailsView1' 触发了未处理的事件 ModeChanging。”

我错过了什么?

4

1 回答 1

0

尝试添加ModeChanging事件处理程序:

protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
{
    DetailsView1.ChangeMode(e.NewMode);
    Data_Bind();
}
于 2012-07-23T02:53:44.620 回答