
protected System.Web.UI.WebControls.DataGrid DataGrid1;
public int KeyID
 ...{
get
 ...{
object o =ViewState ["KeyID"];
if(o!=null)
 ...{
return int.Parse(ViewState ["KeyID"].ToString());
}
else
 ...{
return 0;
}
}
set
 ...{
ViewState ["KeyID"] = value;
}
}
public int RowState
 ...{
get
 ...{ return int.Parse(ViewState ["RowState"].ToString());
}
set
 ...{
ViewState ["RowState"] = value;
}
}
private void Page_Load(object sender, System.EventArgs e)
 ...{
if(IsPostBack)
 ...{return ;
}
getData();
}


private void getData()
 ...{
//SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DsnPubs"]);
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Mblog"]);
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("select * from dbo.Honoree", con);
DataGrid1.DataSource = cmd.ExecuteReader();
DataGrid1.DataBind();
con.Close();
}

private bool UpdateData(int ID,int OldState)
 ...{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["Mblog"]);
SqlCommand cmd;
con.Open();
try
 ...{
string strSql="Update Honoree set Status={0} where HonoreeID={1}";
strSql=string.Format(strSql,(OldState==0?1:0).ToString(),ID.ToString());
cmd = new SqlCommand(strSql, con);
cmd.ExecuteNonQuery();
cmd.Dispose();
return true;
}
catch
 ...{
return false;
}
finally
 ...{
con.Close();
con.Dispose();
}
return false;
}


 Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
 ...{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
 /**//// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
 ...{
this.DataGrid1.ItemCreated += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemCreated);
this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
 ...{
if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
 ...{
Button b=(Button)e.Item.FindControl("changeState");
if(b!=null)
 ...{
b.Click+=new EventHandler(b_Click);
}
}
}

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
 ...{
}

private void b_Click(object sender, EventArgs e)
 ...{
Button but = (Button)sender;
DataGrid dg = (DataGrid)but.NamingContainer.NamingContainer;
//此处是关键!!即找到包含按钮的命名容器的上层命名容器
if(dg == null) return;
DataGridItem di =(DataGridItem)but.NamingContainer;
TableCell key= (TableCell)di.Cells[0];
TableCell state= (TableCell)di.Cells[1];

KeyID=(key==null)?0:int.Parse(key.Text);
RowState=(state==null)?0:int.Parse(state.Text);
Response.Write(UpdateData(this.KeyID,this.RowState).ToString());
getData();
}
|