為DataGrid控件添加CheckBox控件列.首先需要為DataGrid控件添加一個模板列,然後向模板列中添加CheckBox控件.
在System.web.UI.webControls命名空間中有一個DataGridItem類,用來表示DataGrid控件中的某項.在該類中有一個FindControl方法,用來在當前的命名容器中搜索指定ID參數的服務器控件,其使用方法如下:
Public virtual Control FindControl(string id);
參數ID:要查找的控件的標識符
返回值:如果指定的控件存在則返回該控件,如果不存在則返回空.
private void Page_Load(object sender, System.EventArgs e)
{
// 在這裡放置使用者程式碼以初始化網頁
if(!IsPostBack)
{
datagriddatabind();
}
}
private void datagriddatabind()
{
string sql="select top 5 * from elogin2";
SqlConnection conn=new SqlConnection(ConfigurationSettings.AppSettings["connstr"].ToString());
SqlDataAdapter da=new SqlDataAdapter(sql,conn);
DataSet ds=new DataSet();
da.Fill(ds,"elogin2");
if(ds.Tables[0].Rows.Count>0)
{
this.DataGrid1.DataSource=ds;
this.DataGrid1.DataBind();
}
}
#region Web Form 設計工具產生的程式碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 此為 ASP.NET Web Form 設計工具所需的呼叫。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 此為設計工具支援所必須的方法 - 請勿使用程式碼編輯器修改
/// 這個方法的內容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.CheckBox chkExport;
if(this.Button1.Text=="全選")
{
//循環設置DataGrid控件中的項
foreach(DataGridItem oDataGridItem in DataGrid1.Items)
{
//建立模板列中CheckBox控件中的項
chkExport=(CheckBox)oDataGridItem.FindControl("chkExport");
//選中
chkExport.Checked=true;
}
this.Button1.Text="全消";
}
else
{
foreach(DataGridItem oDataGridItem in DataGrid1.Items)
{
//建立模板列中CheckBox控件中的項
chkExport=(CheckBox)oDataGridItem.FindControl("chkExport");
//選中
chkExport.Checked=false;
}
this.Button1.Text="全選";
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
System.Web.UI.WebControls.CheckBox chkExport;
String sID;
System.Text.StringBuilder strMsg=new System.Text.StringBuilder("選中項的字段值分別為︰<hr color=red>");
//循環取得DataGrid控件中選定項的值
foreach(DataGridItem oDataGridItem in DataGrid1.Items)
{
chkExport=(CheckBox)oDataGridItem.FindControl("chkExport");
//如果選中則取值
if(chkExport.Checked)
{
sID=((Label)(oDataGridItem.FindControl("Label1"))).Text;
strMsg.Append(sID+"<br><hr color=red>");
}
}
//顯示選中的項
Message.Text=strMsg.ToString();//Message為Label
}
}