asp.net中合并DataGrid行

來源:互聯網
上載者:User
 

例如:

序號            名稱      計量單位
一、工業經濟    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;
    }
    
   }
  }

兩種方法都可以,但是還是第一中方法好,通用性也強,第二種方法如果稍加修改,應該也可以。可能還有其他方法。具體用那種方法不重要,重要的是如何靈活應用基本的知識解決複雜的問題。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.