例如:
序號 名稱 計量單位
一、工業經濟 aaa 萬元
一、工業經濟 bbb 個
合并為:
序號 名稱 計量單位
一、工業經濟 aaa 萬元
bbb 個
只是將第一列的多行合并為一行,怎麼實現?謝謝大家了先!
實現方法:
把笨狼哥的改成這樣試試:
在.aspx頁面,<asp:datagrid>中用
OnPreRender="fDGrid_PreRender">
在.cs檔案:
//合并相同的儲存格
public void fDGrid_PreRender(object sender, System.EventArgs e)
{
if(this.fDGrid.Items.Count <=1)
{
return;
}
col=0;
TableCell oldtc = this.fDGrid.Items[0].Cells[col];
for(int i=1;i<this.fDGrid.Items.Count;i++)
{
TableCell tc = this.fDGrid.Items[i].Cells[col];
if(tc.Text == oldtc.Text)
{
tc.Visible = false;
if(oldtc.RowSpan == 0)
{
oldtc.RowSpan = 1;
}
oldtc.RowSpan = oldtc.RowSpan +1;
oldtc.VerticalAlign = VerticalAlign.Middle;
}
else
{
oldtc = tc;
}
}
}
當然,還可以用ItemDataBound事件來處理。具體細節如下
在.cs檔案中的
InitializeComponent方法中加入:
this.dgContacts.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgContacts_ItemDataBound);
在.cs檔案中的Page_Load中加入:
if (!Page.IsPostBack )
{
lastIndex=0;
}
其中dgContacts為DataGrid的名字
再在 .cs檔案中加入下面的代碼:
int lastIndex;
protected void dgContacts_ItemDataBound(object source,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string isManager = (string)DataBinder.Eval(e.Item.DataItem, "序號");
int inn=e.Item.ItemIndex;
TableCell c;
int col=0;
if (inn>0)
{
if(dgContacts.Items[lastIndex].Cells[col].Text==isManager)
{
c=new TableCell();
c=e.Item.Cells[col];
if(dgContacts.Items[lastIndex].Cells[col].RowSpan==0)
dgContacts.Items[lastIndex].Cells[col].RowSpan=1;
dgContacts.Items[lastIndex].Cells[col].RowSpan+=1;
Response.Write(dgContacts.Items[lastIndex].Cells[col].RowSpan);
e.Item.Cells.Remove(c);
}
else
{
e.Item.Cells[col].Text=isManager;
lastIndex=e.Item.ItemIndex;
}
}
else
{
e.Item.Cells[col].Text=isManager;
}
}
}
兩種方法都可以,但是還是第一中方法好,通用性也強,第二種方法如果稍加修改,應該也可以。可能還有其他方法。具體用那種方法不重要,重要的是如何靈活應用基本的知識解決複雜的問題。