2012-07-23 99 views
-1

我試圖通過編碼從detailsview插入或更新數據到數據庫中。不提供數據源到細節視圖,因爲它非常容易。我想以編程方式進行。詳細信息通過編碼查看插入/更新數據

正如我所說我沒有直接給數據源。我在頁面加載時做了。

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哪些未處理。「

我失蹤了什麼?

+0

你能證明你的DetailsView控件的標記部分 – 2013-07-31 06:25:02

回答

0

嘗試添加ModeChanging事件處理程序:

protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e) 
{ 
    DetailsView1.ChangeMode(e.NewMode); 
    Data_Bind(); 
}