最近研究asp.net,对gridview有些不了解,上网找了些资料汇总如下:
datakeys和datakeynames这两个东西在gridview中是用来关联数据库中的主键的(或者说在gridview中,
它把用datakeynames关联的字段看作是主键)
使用的语法如下:
gridview.DataKeyNames=new string[] {"主键名"};
ps一下:gridview.DataKeyNames=new string[] {"主键名"};这一句要放在page_load中,否则delete事件找不到主键。会出错
而datakeys的用法与gridview.Rows[].Cells[].Controls[]相似。
gridview.Rows[].Cells[].Controls[]这个东西是用来获取gridview在编辑状态下的textbox的(一般是
这个控件,当然还有别的控件)。
rows[]代表行的数组,cells[]代表单元格的数组,controls代表控件(在cells中的控件)。
于是用这三个东西就可准确定位出在gridview中的所有控件了。
至于datakeys,由于它是主键,所以在编辑是它是不可更改的,所以不在控件之内,于是单独用一个对象
来描述它。datakeys[行数]
以前一直不理解cells是个什么意思。只知道它有个细胞的意思(当然也有细小之意)但是,用在这里似
乎不太对哦。在我的心里是想用rows,columns和controls来定义的。但是,外国人眼中,这是不可行的。
行和列是同一个等级啊--外国人就是严谨啊。后来,一个激灵......突然想到在html的表格中不是有
cellspace和cellpadding吗????这两个东西是针对单元格的。原来cell还有个单元格的意思--虽然在
字典上查不到,但是直觉告诉我,没有错,cell就是单元格的意思。一切概念性的问题都解决了!!
行,单元格,单元格中的控件。这三个正好可以定义所有的控件
注意利用gridview.rows[].cells[].controls[]得到的控件,还要进行强制转换才可以使用。
rows代表第几行
{
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.AllowSorting = true;
BindData();
SetGrid();
//ViewState["style"] = "0";
}
}
private void BindData()
{
SqlConnection MyCon = new SqlConnection(ConStr);
string QueryStr = "SELECT customerid,CompanyName,ContactName,Address FROM customers";
SqlDataAdapter Da = new SqlDataAdapter(QueryStr,MyCon);
DataSet Ds = new DataSet();
Da.Fill(Ds,"Customers");
GridView1.DataSource = Ds.Tables[0];
GridView1.DataKeyNames = new string []{"customerid"};
GridView1.DataBind();
}
private void SetGrid()
{
GridView1.AllowPaging = true;
//GridView1.PageSize = 15;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.EditRowStyle.BackColor = Color.Black;
BindData();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
GridViewRow Row = GridView1.Rows[e.NewSelectedIndex];
Response.Write("<script>alert('你选择了ID为" + Row.Cells[3].Text + "的行');</script>");
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
Response.Write("<script>alert('你切换到了第" + (GridView1.PageIndex+1) + "页');</script>");
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow Row = GridView1.SelectedRow;
Row.BackColor = Color.Crimson;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
//防止非法的输入,预防脚本攻击
string CustomerId = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());
string CompanyName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());
string ContactName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());
string Address = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text.ToString());
SqlConnection Con = new SqlConnection(ConStr);
try
{
string UpdateStr = "UPDATE customers SET companyname='" + CompanyName + "',contactname='" + ContactName + "',address='" + Address + "' WHERE customerid='" + ID + "'";
SqlCommand Cmd = new SqlCommand(UpdateStr, Con);
//尽可能晚的打开连接,尽早的关闭连接
Con.Open();
Cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
BindData();
}
catch (Exception ex)
{
Response.Write("<script>alert('编辑出错,请重新填写');</script>");
GridView1.EditIndex = -1;
BindData();
}
//要及时的关闭打开的连接,提高程序的性能
finally
{
Con.Dispose();
}
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string QueryStr = "DELETE FROM customers WHERE customerid='" + ID + "'";
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Cmd = new SqlCommand(QueryStr,Con);
try
{
Con.Open();
Cmd.ExecuteNonQuery();
BindData();
Response.Write("<script>alert('成功删除');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('删除有误,请检查该表是否与其他表有约束');</script>");
}
finally
{
Con.Dispose();
}
}
//当它写为“return confirm(...);”的时候,后边的任何客户端代码都不可能执行,
//因此你注册时设计处理不可能执行。有些所谓的“示例”代码给你这样写的时候,你要注意,
//它应该并不为按钮注册事件处理方法(注册了就很可笑了,因为根本无用),而是通过设置按钮的CommandName来让gridview处理。
//这种写法下,按钮仅仅是提供命令名称和参数。
//如果你要让后边的代码执行,应该写:
//b.Attributes["onclick"] = "if(!confirm('你真的要删除该条记录么?'))return false;";
//*****************************************************************************************************************
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
{
//这种写法不管你点击的是什么,后面的代码都不会执行。
//((Button)e.Row.Cells[2].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('确定要删除/"" + e.Row.Cells[3].Text + "/"吗?')");
//正确的写法
((Button)e.Row.Cells[2].Controls[0]).Attributes["onclick"] = "if(!confirm('你真的要删除" + e.Row.Cells[3].Text + "这条记录么?'))return false;";
//if (e.Row.RowState == DataControlRowState.Edit)
//{
//e.Row.Attributes.Add("onclick", "_doPostBack(""+((Button)e.Row.Cells[1].Controls[0].ClientID.Replace("_", "$_")));
}
}
}
本文来自CSDN博客,转载请标明出处: http://blog.csdn.net/luchuanbo/archive/2009/05/16/4192560.aspx
Property | Description |
---|---|
Attributes | Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.(inherited from WebControl) |
Cells | Gets a collection of TableCell objects that represent the cells of a row in a Table control.(inherited from TableRow) |
DataItem | Gets the underlying data object to which the GridViewRow object is bound. |
RowIndex | Gets the index of the GridViewRow object in the Rows collection of a GridView control. |
RowType | Gets the row type of the GridViewRow object. |
Table 1: Most used properties of the Row
还有就是这一篇:http://www.microsoft.com/taiwan/msdn/columns/huang_jhong_cheng/ASP_NET_GridView.htm