private void Page_Load(object sender, System.EventArgs e)
{
String ConnectionString ;
ConnectionString = "server=localhost;database=northwind;UID=sa";
String CommandText = "Select CategoryName, ProductName,Cast(UnitPrice as varchar(50)) as UnitPrice, UnitsInStock from Products INNER JOIN Categories On Products.categoryID = Categories.CategoryID order by Products.categoryID"; SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter myCommand = new SqlDataAdapter(CommandText, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
String curCat ;// ‘指示当前记录中产品所属的类别
String prevCat="" ;// ‘指示上一条记录中产品所属的类别
//TableRow row; // ‘要插入分类标题的行
int i = 0;// ‘要插入分类标题行的位置,用I表示 //'遍历结果集,找出要插入分类标题的行
while (i <= ds.Tables[0].Rows.Count - 1)
{
curCat = ds.Tables[0].Rows[i]["CategoryName"].ToString();
if (curCat != prevCat)
{
//‘如果发现前后两记录的所属类别不一样
prevCat = curCat;
DataRow shRow = ds.Tables[0].NewRow();
shRow["ProductName"] = ds.Tables[0].Rows[i][0];
// ‘修改行的标题为分类标题名
shRow["UnitPrice"] = "SubHead" ; //‘设置一个临时的标记
ds.Tables[0].Rows.InsertAt(shRow, i); //‘插入新的分类标题行
i += 1;
}
i += 1;
}
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
{
String ConnectionString ;
ConnectionString = "server=localhost;database=northwind;UID=sa";
String CommandText = "Select CategoryName, ProductName,Cast(UnitPrice as varchar(50)) as UnitPrice, UnitsInStock from Products INNER JOIN Categories On Products.categoryID = Categories.CategoryID order by Products.categoryID"; SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter myCommand = new SqlDataAdapter(CommandText, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds);
String curCat ;// ‘指示当前记录中产品所属的类别
String prevCat="" ;// ‘指示上一条记录中产品所属的类别
//TableRow row; // ‘要插入分类标题的行
int i = 0;// ‘要插入分类标题行的位置,用I表示 //'遍历结果集,找出要插入分类标题的行
while (i <= ds.Tables[0].Rows.Count - 1)
{
curCat = ds.Tables[0].Rows[i]["CategoryName"].ToString();
if (curCat != prevCat)
{
//‘如果发现前后两记录的所属类别不一样
prevCat = curCat;
DataRow shRow = ds.Tables[0].NewRow();
shRow["ProductName"] = ds.Tables[0].Rows[i][0];
// ‘修改行的标题为分类标题名
shRow["UnitPrice"] = "SubHead" ; //‘设置一个临时的标记
ds.Tables[0].Rows.InsertAt(shRow, i); //‘插入新的分类标题行
i += 1;
}
i += 1;
}
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
{
//’如果发现是分类标题行的话,则对其进行格式化
if (e.Item.Cells[1].Text.Equals("SubHead"))
{
//’设置列宽
// 'Set the cell to a ColSpan of 3
e.Item.Cells[0].ColumnSpan = 3;
//‘合拼为一个新的分类标题行,移除其中的单元格
e.Item.Cells.RemoveAt(2);
e.Item.Cells.RemoveAt(1);
e.Item.Cells[0].Attributes.Add("align", "Left");
e.Item.Cells[0].Font.Bold = true;
e.Item.BackColor = Color.FromArgb(204,204,255);
}
}
另外,我现在的目的是在一个DataSet中的2个表中查找、筛选数据,数据已经到内存中了,你仔细看一下我的问题,多交流:[email protected]