GridView 总结
1、GridView1_RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//这里的处理是为了回显之前选中的情况
if (e.Row.RowIndex > -1 && this.SelectedItems != null)
{
DataRowView row = e.Row.DataItem as DataRowView;
CheckBox cb = e.Row.FindControl("CheckBox1") as CheckBox;
if (this.SelectedItems.Contains(row["file_id"].ToString()))
cb.Checked = true;
else
cb.Checked = false;
}
//改变颜色
if (e.Row.RowType == DataControlRowType.DataRow)
{
//得到正在被创建的项的称呼
string uploadState = (string)DataBinder.Eval(e.Row.DataItem, "file_uploadstate");
//变颜
if (uploadState == "1")
{
e.Row.BackColor = System.Drawing.Color.LightPink;
e.Row.ForeColor = System.Drawing.Color.Maroon;
}
else if (uploadState == "2")
{
e.Row.BackColor = System.Drawing.Color.LightCyan;
e.Row.ForeColor = System.Drawing.Color.DarkBlue;
}
}
}
2、分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
InitPage();
}
//重新绑定
private void InitPage()
{
GridViewBind2();
}
3、行删除
首先在GridView的<Columns></Columns>内添加
<asp:CommandField ShowDeleteButton="True" HeaderText="操作" />
后添加GridView1_RowDeleting(行删除事件)
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string strSql = "delete from archives where ar_id=" + id;
try
{
SqlConnection conn = new SqlConnection(strConn);
if (conn.State.ToString() == "Closed")
conn.Open();
SqlCommand comm = new SqlCommand(strSql, conn);
comm.ExecuteNonQuery();
comm.Dispose();
if (conn.State.ToString() == "Open")
conn.Close();
GridView1.EditIndex = -1;
GridViewBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
}
4、GridView中的值自动换行或不换行
GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
加到DataBound事件里面去
或放到
protected void Page_Load(object sender, EventArgs e)
{
//正常换行
GridView1.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
//下面这行是自动换行
GridView1.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
if (!IsPostBack)
{
bind();//调用数据绑定即可
}
}
浙公网安备 33010602011771号
