using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class d21 : System.Web.UI.Page
{
//將dataset 和 sqldataAdapter這兩個物件置頂,方便各函數呼叫
DataSet ds = new DataSet();
SqlDataAdapter da ;
protected void Page_Load(object sender, EventArgs e)
{
//如果第一次載入頁面,則執行和gridview的數據綁定,並將sqldataApter和dataset的內容,傳給session,以便postBack時,能記住目前的資料
if (!IsPostBack)
{
dbInit();
Session["ds"] = ds;
Session["da"] = da;
}
}
private void dbInit()
{
//gridview與數據的綁定
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString);
try
{
da = new SqlDataAdapter("select id,real_name,sex from db_user", conn);
SqlCommandBuilder sb = new SqlCommandBuilder(da);
da.Fill(ds, "user");
da.FillSchema(ds,SchemaType.Source, "user");
GridView1.DataSource = ds.Tables["user"].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
dbInit();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
dbInit();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
dbInit();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
RadioButtonList rl;
//判斷目前row的狀態,是一般列、分隔列、編輯列…
if (e.Row.RowState.ToString().IndexOf("Edit")>=0)
{
rl = e.Row.FindControl("RadioButtonList2") as RadioButtonList;
}
else
{
rl = e.Row.FindControl("RadioButtonList1") as RadioButtonList;
}
//利用find的方法,可以偵測目前列的主索引值
DataRow row = ds.Tables["user"].Rows.Find(GridView1.DataKeys[e.Row.RowIndex].Value);
if (rl.Items[0].Value == row["sex"].ToString())
{
rl.Items[0].Selected = true;
}
else
{
rl.Items[1].Selected = true;
}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataSet ds = Session["ds"] as DataSet;
DataRow row = ds.Tables["user"].Rows.Find(Convert.ToInt32( GridView1.DataKeys[e.RowIndex].Value));
RadioButtonList rl = GridView1.Rows[e.RowIndex].FindControl("RadioButtonList2") as RadioButtonList;
TextBox t1=GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
row["real_name"] = t1.Text;
row["sex"] = rl.SelectedValue;
SqlDataAdapter da = Session["da"] as SqlDataAdapter;
da.Update(ds,"user");
Session["ds"] = ds;
Session["da"] = da;
GridView1.EditIndex = -1;
dbInit();
}
}
留言列表