要在ASP.NET2.0中使用GridView控件操作数据,需要遵循以下步骤:
1.在页面中引入GridView控件
使用以下代码在页面中引入GridView控件:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
2.在代码中绑定数据源
绑定数据源的过程包括:创建连接字符串、创建连接对象、创建命令对象、执行查询语句、将查询结果保存到DataSet对象中。
string connString = "Data Source=server;Initial Catalog=mydb;User ID=username;Password=password";
SqlConnection conn = new SqlConnection(connString);
string sqlString = "SELECT * FROM mytable";
SqlDataAdapter da = new SqlDataAdapter(sqlString, connString);
DataSet ds = new DataSet();
da.Fill(ds, "mytable");
3.将查询结果绑定到GridView控件
使用以下代码将查询结果绑定到GridView控件:
GridView1.DataSource = ds.Tables["mytable"].DefaultView;
GridView1.DataBind();
- GridView控件的常用属性
GridView控件包括常用的属性,如AutoGenerateColumns、PageSize、PageIndex、ShowHeader等。示例如下:
GridView1.AutoGenerateColumns = false; //关闭列自动生成
GridView1.PageSize = 10; //设置每页显示数据条数
GridView1.PageIndex = 0; //设置当前显示页数
GridView1.ShowHeader = true; //显示GridView表头
- GridView控件的事件处理
GridView控件包括常用的事件,如RowDataBound、RowCommand、SelectedIndexChanged等。示例如下:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//对每一行进行操作
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
//删除数据
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//选择数据
}
上述是使用GridView控件操作数据的基本攻略。下面给出两个示例说明。
示例1: 实现数据分页
protected void btnPageIndex_Click(object sender, EventArgs e)
{
int pageIndex = int.Parse(txtPageIndex.Text);
string connString = "Data Source=server;Initial Catalog=mydb;User ID=username;Password=password";
SqlConnection conn = new SqlConnection(connString);
string sqlString = "SELECT * FROM mytable";
SqlDataAdapter da = new SqlDataAdapter(sqlString, connString);
DataSet ds = new DataSet();
da.Fill(ds, "mytable");
GridView1.DataSource = ds.Tables["mytable"].DefaultView;
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
GridView1.PageIndex = pageIndex - 1;
GridView1.DataBind();
}
示例2: 实现数据删除
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string id = row.Cells[0].Text;
string connString = "Data Source=server;Initial Catalog=mydb;User ID=username;Password=password";
SqlConnection conn = new SqlConnection(connString);
string sqlString = "DELETE FROM mytable WHERE id='" + id + "'";
SqlCommand cmd = new SqlCommand(sqlString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataBind();
}
}
以上就是在ASP.NET2.0中使用GridView控件操作数据的详细攻略,希望能够有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:ASP.NET2.0中用Gridview控件操作数据的代码 - Python技术站