分頁
protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
this.DataGrid1.CurrentPageIndex = e.NewPageIndex;
this.datagridview();
}
隱藏列
this.DataGrid1.Columns[2].Visible = false;// 隱藏第三列(只是表面上的隱藏)
this.datagridview();
滑鼠經過每行時高亮顯示:
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");
}
}
雙向排序:
DataGrid1 的 SortCommand 事件啟用排序事件
protected void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
{
if (ViewState["order"] == null)
{
ViewState["order"] = "ASC";//viewstate[""]同session[""] 差不多,儲存在用戶端
}
else
{
if (ViewState["order"].Tostring() == "ASC")
{
ViewState["order"] = "DESC";
}
else
{
ViewState["order"] = "ASC";
}
}
SqlConnection con = connecttion.ado.sqldb();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand("select * from person", con);
DataSet ds = new DataSet();
sda.Fill(ds, "person");
ds.Tables["person"].DefaultView.Sort = e.SortExpression + " " + ViewState["order"].ToString();
//預設視圖的Sort屬性就是排序屬性 e.SortExpression 就是屬性產生器中排序運算式的欄位
this.DataGrid1.DataSource = ds.Tables["person"].DefaultView;//
this.DataGrid1.DataBind();
}
綁定查看詳細資料列
在show.aspx中用 string id = Request.QueryString["id"] 接收。
datagrid中 DataKeyfield="id" 按照索引取的,使用時可以取得當前行的id
當要刪除或者修改每一行時通過 this.DataGrid1.DataKeys[e.Item.ItemIndex]來獲得當前行的id
datagrid刪除的實現
首先在屬性產生器中添加刪除按鈕,然後在dadagrid的DeleteCommand 事件中編寫代碼即可
protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
{
string id = this.DataGrid1.DataKeyField[e.Item.ItemIndex];
SqlConnection con = connecttion.ado.sqldb();
con.Open();
SqlCommand cmd=new SqlCommand("delete from person where pid='"+id+"'",con);
cmd.ExecuteNonQuery();
this.datagridview();
}
如果要在刪除時顯示確認後 再刪除功能
在DataGrid1_ItemDataBound的事件中 加第三行就可以了
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)//普通行和交錯行的事件
{
e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");//滑鼠在的時候
e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c");//滑鼠離開的時候
((LinkButton)(e.Item.Cells[4].Controls[0])).Attributes.Add("onclick", "return confirm('確認刪除嗎?')");//點任一行的第5列時觸發的事件
}
}
Datagrid 的編輯功能:
更新:
string id = this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();取的更新行的id
string pname = ((TextBox)(e.Item.Cells[1].Controls[0])).Text; 取的本行第二個欄位文字框的值
string psex = ((TextBox)(e.Item.Cells[2].Controls[0])).Text;
下面加入資料庫就可以了,
在更新時可使用驗證控制項進行驗證,首先把那一列在屬性產生器中 轉換成模板列,然後在模板中添加驗證控制項就可以了。