原贴子在这里:http://www.tiantiansoft.com/bbs/dispbbs.asp?boardID=40&ID=90753
现在知道的有三种绑定数据到DataGrid的方法,有四种方法清除数据的方法
一、使用DataReader绑定数据到DataGrid,用重新检索数据的方法清除数据
绑定数据的方法
private void DataGrid_r_DataReader()
{
//使用DataReader绑定数据到DataGrid
string strConnection="Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("/data/my#data.mdb");
OleDbConnection MyConnection=new OleDbConnection(strConnection);
MyConnection.Open();
string mysql="select * from students";
OleDbCommand MyCommand=new OleDbCommand(mysql,MyConnection);
OleDbDataReader dr=MyCommand.ExecuteReader();
DataGrid3.DataSource=dr;
DataGrid3.DataBind();
dr.Close();
MyConnection.Close();
}
清除时只是把上边的方法重新调用一回,就改sql语句为这个:
string mysql="select * from students where 1=2";
因为得到的结果集是空的,所以肯定数据会给完全清除掉
二、使用DataSet绑定数据到DataGrid
绑定数据的方法:
private void DataGrid_r_DataSet()
{
//使用DataSet绑定数据到DataGrid
string strConnection="Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("/data/my#data.mdb");
string mysql="select * from students";
OleDbDataAdapter da = new OleDbDataAdapter(mysql, strConnection);
DataSet ds = new DataSet();
da.Fill(ds,"stu");
DataGrid1.DataSource = ds;
DataGrid1.DataMember = "stu";
DataGrid1.DataBind();
}
清除数据的方法:
private void Button1_Click(object sender, System.EventArgs e)
{
//使用DataSet的子集重新绑定数据的方法
if(DataGrid1.DataSource!=null)
{
((DataSet)DataGrid1.DataSource).Tables[0].Rows.Clear();
DataGrid1.DataBind();
}
}
三、使用DataView绑定数据到DataGrid
绑定数据的方法:
private void DataGrid_r_DataView()
{
//使用DataView绑定数据到DataGrid
string strConnection="Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + Server.MapPath("/data/my#data.mdb");
string mysql="select * from students";
OleDbDataAdapter da = new OleDbDataAdapter(mysql, strConnection);
DataSet ds = new DataSet();
da.Fill(ds,"stu");
DataView dv = ds.Tables["stu"].DefaultView;
DataGrid2.DataSource = dv;
DataGrid2.DataBind();
}
清除数据的方法:
private void Button2_Click(object sender, System.EventArgs e)
{
//使用DataView的子集重新绑定数据的方法
DataView dv=new DataView();
dv=(DataView)DataGrid2.DataSource;
if(dv!=null)
{
dv.RowFilter = "1 = 2";
dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
dv.Sort = "student_name DESC";
DataGrid2.DataSource = dv;
DataGrid2.DataBind();
}
}
四、使用循环删除行的方法删除数据,可以用于各种数据绑定的方式的:
for(int i=0;i<DataGrid1.Items.Count;i++)
{
DataGrid1.Items[i].Visible=false;
}
上边四种方法可以清空DataGrid里的数据,看到红色的地方了没?对每个取DataGrid的DataSource属性的,我都加了判断是没是null值的,因为我一开始的时候把检索数据到DataGrid的代码全放在了Page_Load事件里,而且是这样子来的:
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
DataGrid_r_DataView();
DataGrid_r_DataReader();
DataGrid_r_DataSet();
}
}
当页面因服务器控件而重新加载的时候,DataGrid没有重新检索数据,他们的DataSource属性,会全被置为null
所以上边四种方法,真正用的方便的只有第四种,第二第三种方法都需要在一开始的时候记录相DataGrid的DataSource属性才成
最后提出的问题是:嘛干因服务器控件而重新加载页面时,DataGrid没有重新检索,他们的DataSource属性全被置为了null,可是数据却还会保留呢?
有人回答了这一句:欧阳文枫.net(18817240) 20:24:31 ds会回置的
不过具体的还是没搞懂