天道酬勤,学无止境

How to merge multiple columns values into one column? Asp.net Gridview C#

First of I don't know if this is possible, the correct way to go or even will work, but I hope you guys can help me out, I will try to explain:

I have a GridView Control on the ASPX page:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" OnRowDataBound="GridView1_RowDataBound" GridLines="None" CssClass="table table-striped" />

I created a DataTable in the code-behind which holds the following data and have bind it to the Gridview control:

-----------------------------------------
|       | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1  | 1     | 1     | 1     | 1b    |
| Row2  | 1a    | 2b    | 2b    | 4b    |
| Row3  | 2a    | 2c    | 2a    | 2a    |
| Row4  | 1d    | 1d    | 1d    | 4d    |
| Row5  | 1e    | 1e    | 1e    | 1e    |
| Row6  | 1f    | 2f    | 3f    | 4f    |
-----------------------------------------

Now I would like matching column values to be merged and add the appropriate colspan. I have added to the GridView control a OnRowDataBound as following:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.RowIndex >= 0)
        {
            int colSpanValue = 2;
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (i+1 < e.Row.Cells.Count) 
                {
                    if (e.Row.Cells[i].Text == e.Row.Cells[i + 1].Text)
                    {
                        e.Row.Cells[i].BackColor = Color.Beige;
                        e.Row.Cells[i].ColumnSpan = colSpanValue;
                        e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Center;
                        e.Row.Cells[i + 1].Visible = false;
                        colSpanValue++;
                    }
                }
            }
        }
    }
}

so the above data would like this, something like this.

-----------------------------------------
|       | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1  |       1       | 1b            | <!-- problem
| Row2  | 1a    |      2b       | 4b    |
| Row3  | 2a    | 2c    |      2a       | <!-- problem
| Row4  |           1d          | 4d    |
| Row5  |              1e               |
| Row6  | 1f    | 2f    | 3f    | 4f    |
-----------------------------------------

Currently I managed to get this, see screenshot

However this is not really what i would like to see, but would expect as the OnRowDataBound code block is probably not done the right.

So my question is:

  • How could I merge all equal columns in a row and add colspan to them?
  • Now for the tricky bit, would I be able to sort the columns so, that matching column cells are displayed properly? (not sure about this)

So the ideal result would be like this:

-----------------------------------------
|       | Name1 | Name2 | Name3 | Name4 |
-----------------------------------------
| Row1  |           1           | 1b    | <!-- problem
| Row2  | 1a    |      2b       | 4b    |
| Row3  | 2a    | 2c    |      2a       | <!-- problem
| Row4  |           1d          | 4d    |
| Row5  |              1e               |
| Row6  | 1f    | 2f    | 3f    | 4f    |
-----------------------------------------

UPDATED INFORMATION

After updating the code according to the answers provided by ConnorsFan and fnostro, both answers are correct and work, thank you for the help. I choose for ConnorsFan's approach, as i'm still learning.

The collspan's are now correct, see screenshot below:

I will try to fnostro's advise to manage the sorting part via the DataTable and rebind the data to the GridView1 and keep you posted. once again thank you for your answers.

评论

You can try this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        for (int i = 0; i < e.Row.Cells.Count - 1; i++)
        {
            TableCell cell = e.Row.Cells[i];

            if (cell.Visible)
            {
                int colSpanValue = 1;

                for (int j = i + 1; j < e.Row.Cells.Count; j++)
                {
                    TableCell otherCell = e.Row.Cells[j];

                    if (otherCell.Text == cell.Text)
                    {
                        colSpanValue++;
                        otherCell.Visible = false;
                    }
                    else
                    {
                        break;
                    }
                }

                if (colSpanValue > 1)
                {
                    cell.ColumnSpan = colSpanValue;
                    cell.BackColor = Color.Beige;
                    cell.HorizontalAlign = HorizontalAlign.Center;
                }
            }
        }
    }
}

Regarding sorting. It's better to manage sorting in the DataTable and simply rebind to the GridView

Here is how I modified the RowDataBound Event to merge like data:

    protected void GridView1_RowDataBound( object sender, GridViewRowEventArgs e ) 
    {
      if ( e.Row.RowType == DataControlRowType.DataRow ) 
      {
        // loop through cells and track span index (si)
        for ( int i = 0, si = 0; i < e.Row.Cells.Count; si = i) 
        {
          // compare adjacent cells for like data and hide as needed
          while ( ++i < e.Row.Cells.Count && e.Row.Cells[ si ].Text == e.Row.Cells[ i ].Text )
            e.Row.Cells[ i ].Visible = false;

          // set span and, conditionally, special formatting
          if ( ( e.Row.Cells[ si ].ColumnSpan = ( i - si ) ) > 1 ) 
          {
            e.Row.Cells[ si ].BackColor = Color.Beige;
            e.Row.Cells[ si ].HorizontalAlign = HorizontalAlign.Center;
          }
        }
      }
    }

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 基于行级c#对asp.net gridview控件进行排序(Sorting asp.net gridview control based on row level c#)
    问题 我的问题与早期关于 stackoverflow 的问题有关。 在我之前的问题中,我需要在 ac# asp.net Gridview 控件中合并具有相同值的列。 这个问题是通过其他stackoverflowers的出色帮助和支持解决的,但是我还需要在行级别对订单进行排序,例如: 当前格式: gridview 控件允许我按列(从上到下)对值进行排序,但是有没有办法对行进行排序,例如:在行级别从左到右,如果您查看(当前格式)屏幕截图并检查行3,您将看到以下结果:( 2a, 2c, 2x2a, 2c ) 现在理想情况下,我想将它们组合在一起,如 ( 3x2a, 2x2c ),但不确定这是否是正确的方法,因为它涉及移位整个列,我可以想象,如果我们对第一行进行正确排序并转到第二行,我们可能会再次弄乱第一行结果,不确定这是否可行,甚至可能。 我想让我的 gridview 控件显示如下数据: 所需格式: 这是在asp.net gridview控件中的方法或可实现的吗? 否则我如何能够实现理想的解决方案? 如果您需要任何其他信息,请询问,我会尝试扩展我的问题。 更新信息: 在ConnersFan 的建议之后,我得到了以下结果,这个想法有点存在,但还没有。 运行页面后,我得到了这个屏幕截图,在每个屏幕截图之后,我将解释会发生什么: ^^^ DEFAULT PAGE LOAD
  • Sorting asp.net gridview control based on row level c#
    My issue is related to an earlier question on stackoverflow. In my previous question I needed to merge columns with the same values in a c# asp.net Gridview Control. This problem was resolved by the excellent help and support from other stackoverflowers, however I'm also required to sort the order on row level e.g: Current format: The gridview control allows me to sort values by columns (top to bottom) however would there be a way to sort the rows, e.g: left to right on row level, if you take a look at the (Current format) screenshot and check row 3, you will see the following result: ( 2a, 2c
  • 在更新行时获取 DataField 值 (asp GridView) asp.NET C#(Get DataField value while updating row (asp GridView) asp.NET C#)
    问题 我的.aspx文件中有一个 GridView 控件,它由我的表( Id 、 Surname )填充: <asp:GridView ID="gridView_1" runat="server" AutoGenerateColumns="False" <!-- used to customize my columns --> DataKeyNames="Id" DataSourceID="sqlDataSource_1" OnRowUpdating="gridView_rolesTiers_RowUpdating"> <Columns> <asp:BoundField DataField="dbColumn_db" HeaderText="Id" InsertVisible="False" ReadOnly="True" /> <asp:BoundField DataField="dbColumn_Surname" HeaderText="Surname" SortExpression="RLT_Intitule"> <asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView> 我有一个关联的 SqlDataSource,它允许我使用存储过程来显示我的姓氏: <asp:SqlDataSource ID=
  • 如何从 ASP.NET (C#) 中的 Gridview 行更新 Excel 文件?(How To Update an Excel File From a Gridview Row in ASP.NET (C#)?)
    问题 我正在尝试一个简单的程序。 当用户单击按钮时,TextBox1 的值针对存储的过程运行,返回客户 ID。 在 Excel 工作表中查找该客户 ID。 如果找到,则将相应行的信息绑定到 Gridview。 但是,完成此操作后,我想将该行写入从中提取信息的 excel 文件的第二张表。 代码有点乱,因为我在这个过程中尝试了一些不同的东西。 当前 Excel 文件已保存,但当然当前存在的行会被覆盖,因此始终只有一行。 将数据从 Gridview(仅保留一行)更新(或插入)到 Excel 文件上的工作表的最简洁、最简单的方法是什么? 基本上,这将一遍又一遍地完成(当用户输入一个数字并单击事件按钮时),因此第二个工作表(Sheet2)中的行将不断从 Gridview 更新。 任何帮助表示赞赏。 如果这听起来/看起来很业余,我深表歉意。 protected void Button1_Click(object sender, EventArgs e) { if (TextBox1.Text != "") { DateTime saveNow = DateTime.Now; long numCardNumber; string strCardNumber; // Card number (stored as string) char[] MyChar = { ';', '?' }; //
  • 无法将数据从一个 GridView 复制到另一个 ASP.NET C#(Cannot copy data from one GridView to anther ASP.NET C#)
    问题 我是 C# ASP.NET 的新手,我的项目由 2 个 GridViews 组成,第一个 GridView 显示来自 SQL 服务器的数据,并且工作正常。 现在我需要实现的是,当我们从 gridView 1 中选择任何行时,这些行应该被复制到 GridView 2。 下面是我的代码: protected void Button1_Click(object sender, EventArgs e) { SqlConnection sc = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=x;Integrated Security=True"); sc.Open(); SqlDataAdapter sd = new SqlDataAdapter("select * from BookDetails", sc); DataSet ds = new DataSet(); sd.Fill(ds, "BookDetails"); sc.Close(); GridView1.DataSource = ds; GridView1.DataBind(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
  • How To Update an Excel File From a Gridview Row in ASP.NET (C#)?
    I am attempting a simple program. When the user clicks the button, the value of TextBox1 is run against a stored proc, returning a Customer ID. That Customer ID is looked up in an Excel sheet. If found, the information for the corresponding row is bound to a Gridview. However, once this is done, I would like to write THAT row to the second sheet of the excel file the info was pulled from. The code is a bit messy, as I'm trying a few different things in the process. Currently the Excel file is saved, but of course the row that is currently there, is overwritten, so there will always be just one
  • 如何在 ASP.NET 和 C# 中使用 iTextSharp 合并 PDF 中具有相同值的行?(How to merge rows with same value in PDF using iTextSharp, in ASP.NET and C#?)
    问题 我有下一个问题: 我需要为此表合并具有相同值的行: 我需要的表 该表在 GridView 中,我实现了合并该行的方法 private void AgruparGridView(GridViewRowCollection rows, int indiceInicial, int totalCeldasAgrupar) { //Si no hay celdas a agrupar no realiza ninguna acción if (totalCeldasAgrupar == 0) return; int i, count = 1; ArrayList lst = new ArrayList(); // Los elementos del gridview son llenados en la lista. lst.Add(rows[0]); var ctrl = rows[0].Cells[indiceInicial]; //Recorrer los registros que se tengan para agrupar for (i = 1; i < rows.Count; i++) { TableCell nextCell = rows[i].Cells[indiceInicial]; if (ctrl.Text == nextCell.Text) { count+
  • 如何在 GRid View asp.net C# 的一列中显示两个属性(How to show two properties in one column of GRid View asp.net C#)
    问题 我有类 Person,有两个属性 First Name 和 Last Name,如果我将 person 数组设置为 GridView 的数据源,我如何在一列中同时显示名字和姓氏?/ 谢谢 回答1 使用模板字段和 Eval 方法: <asp:GridView runat="server" ID="MyGrid" AutoGenerateColumns="false" DataSourceId="..."> <Columns> <asp:TemplateField> <ItemTemplate> <%# Eval("FirstName") %> <%# Eval("LastName") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 回答2 如果你不介意在代码隐藏中做这件事,这里是如何做的。 在 GridView 中放置一个TemplateField ,在ItemTemplate包含一个 Label,并将 GridView 的 RowDataBound 事件连接到一个处理程序: <asp:GridView runat="server" ID="PeopleGridView" AutoGenerateColumns="false" OnRowDataBound="PeopleGridView
  • 如何在GridView C#asp.net中将超链接添加到边界域(How to add hyperlink to boundfield in gridview c# asp.net)
    问题 我在aspx页面中有一个gridview,一旦用户单击Component1值,就需要它从BoundField向该Component添加超链接。 如何将超链接添加到与BoundField相关的boundfield? <asp:GridView ID="Module" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="dsrcGetModuleData" Font-Size="0.65em" ForeColor="Black" GridLines="Vertical" DataKeyNames="TestID"> <FooterStyle BackColor="#CCCC99" /> <Columns> <asp:BoundField DataField="Component1" ItemStyle-Font-Size="Small" HeaderStyle-Width="80px" HeaderStyle-Font-Size ="Medium" SortExpression="Component1" /> </Columns>
  • 超链接参考另一列 DevExpress Gridview ASP.Net Webform(Hyperlink Reference to another column DevExpress Gridview ASP.Net Webform)
    问题 我正在使用 for 循环将列添加到使用 VB.Net 的 DevExpress ASP.Net WebForms GridView。 我能够获得一个超链接来引用相同的列值: Dim newColumn As New DevExpress.Web.GridViewDataHyperLinkColumn newColumn.PropertiesHyperLinkEdit.NavigateUrlFormatString = "TrendView.aspx?CurrentID={0}" 我需要以编程方式将超链接设置为另一列的值......即第三列需要有一个引用同一行中第一列值的超链接。 如何在运行时使用 VB 或 C# 访问该行中的另一列? 回答1 请参考此网址来解决您的问题 https://www.devexpress.com/Support/Center/Example/Details/E308 将您的填充网格逻辑更改为 ASPX : <dx:ASPxGridView ID="ASPxGridView1" runat="server"></dx:ASPxGridView> CS protected void Page_Init(object sender, EventArgs e) { ASPxGridView1.KeyFieldName = "ID"
  • 在asp.net C#中搜索gridview(searching gridview in asp.net C#)
    问题 我正在尝试寻找一种使用 C# 编程语言在 asp.net 中搜索网格视图的方法。 我不希望网格视图启用分页。 我希望它显示输入的结果。例如,如果我输入了“s”,则所有以 s 开头的记录都将只可见。 我查看了一些在代码中包含数据绑定的站点。 GridView1.DataSource = dt; GridView1.DataBind(); 我需要这个吗? 这有什么作用? 我能否获得一些可以回答我的问题的建议或链接的帮助。 谢谢你。 回答1 这是一个完整的工作示例。 您想稍微调整一下以适应您自己的需要。 正如 Murray Foxcroft 所指出的,您会在本示例中找到几个DataBindings来使事情发挥作用。 <asp:TextBox ID="searchBox" runat="server"></asp:TextBox> <asp:Button ID="searchButton" runat="server" Text="search" OnClick="searchButton_Click" /> <asp:Button ID="reset" runat="server" Text="reset" OnClick="resetSearchButton_Click" /> <br /> <br /> <asp:GridView ID="GridView1" runat=
  • c#asp.net在gridview中显示图像(c# asp.net displaying image in gridview)
    问题 我希望在 gridview 中显示图像。 我有一个包含 4 列的数据库 - id、作者、评论、文件名(其中包含 img 路径) http://postimg.org/image/4loz8t9fb/ 我有一个图片上传方法,所以当用户写他的评论,选择一张照片并点击提交 - 他的名字,评论和照片路径进入数据库(照片本身上传到项目文件夹中的“图像”文件夹)。 <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False" Font-Names = "Arial" Height="375px" Width="498px" DataSourceID="SqlDataSource2" > <Columns> <asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" /> <asp:BoundField DataField="Comment" HeaderText="Comment" SortExpression="Comment" /> <asp:BoundField DataField="FileName" HeaderText="FileName" SortExpression="FileName" /
  • c# asp.net displaying image in gridview
    I wish to display an image in a gridview. I have a database with 4 columns - id, author, comment, filename (which holds the img path) http://postimg.org/image/4loz8t9fb/ I have an image upload method so when the user writes his comment, chooses a photo and clicks submit- his name, the comment and the photo path goes to the database (and the photo itself is uploaded to 'Images' folder in the project folder). <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False" Font-Names = "Arial" Height="375px" Width="498px" DataSourceID="SqlDataSource2" > <Columns> <asp:BoundField
  • GridView-在空数据源上显示标题(GridView - Show headers on empty data source)
    问题 在C#中,即使数据源为空,我仍如何显示gridview的标题。 我不是自动生成列,因为它们都是预定义的。 目前我正在做的事情如下。 从存储过程中获取一个DataTable,然后设置gridview的DataSource,然后调用DataBind()。 当我有数据时,这很好用,但是当不返回任何行时,我只是得到网格应位于的空白位置。 编辑:感谢所有的.NET 4+属性。 我在.NET 3.5天内问过这个问题。 现在,这要容易得多。 :) 回答1 ASP.Net 4.0添加了布尔值ShowHeaderWhenEmpty属性。 http://msdn.microsoft.com/zh-CN/library/system.web.ui.webcontrols.gridview.showheaderwhenempty.aspx <asp:GridView runat="server" ID="GridView1" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false"> <Columns> <asp:BoundField HeaderText="First Name" DataField="FirstName" /> <asp:BoundField HeaderText="Last Name" DataField="LastName"
  • Get DataField value while updating row (asp GridView) asp.NET C#
    I have a GridView control in my .aspx file which is filled by my table (Id, Surname) : <asp:GridView ID="gridView_1" runat="server" AutoGenerateColumns="False" <!-- used to customize my columns --> DataKeyNames="Id" DataSourceID="sqlDataSource_1" OnRowUpdating="gridView_rolesTiers_RowUpdating"> <Columns> <asp:BoundField DataField="dbColumn_db" HeaderText="Id" InsertVisible="False" ReadOnly="True" /> <asp:BoundField DataField="dbColumn_Surname" HeaderText="Surname" SortExpression="RLT_Intitule"> <asp:CommandField ShowEditButton="True" /> </Columns> </asp:GridView> I have an associated
  • C#从gridview asp net的下拉列表中获取选定的值(C# getting selected value from dropdownlist in gridview asp net)
    问题 每当 gridview 中的下拉列表的值发生变化时,如何更改文本框的值? 在页面加载时,文本框显示所选值,但是当我更改下拉列表的选择时,文本框值不会更改。 代码如下。 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"> <Columns> <asp:TemplateField HeaderText="Entry"> <ItemTemplate> <%# Container.DataItemIndex + 1 %> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Duty"> <ItemTemplate> <asp:DropDownList ID="duty" runat="server" OnLoad = "ddl1_load" OnSelectedIndexChanged="duty_SelectedIndexChanged" autopostback="true" EnableViewState="true"></asp:DropDownList> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 后面的代码如下
  • 如何减少gridview列asp.net C#中的小数位(how to decrease decimal places in gridview column asp.net C#)
    问题 我想在 gridview 列中只显示 2 个小数位。 列名称为 InsuaranceAmount、TotalAmount 和 TravelAssistAmoun。 for (int i = 0; i < bookingDetailsEmailRS.Length - 1; i++) { BookingDetailsEmailRS[] bookingDetailsEmailRS = b.GetBookingDetails(soap, emailid, out errorCode, out errorAtNode); GridView1.DataSource = bookingDetailsEmailRS.Select(obj => new { TravelerName = obj.Travelers[0].FirstName + obj.Travelers[0].MiddleName + obj.Travelers[0].LastName, obj.BookingNumber, obj.BookingStatus, obj.ContactNumber, obj.CouponDiscountAmount, obj.DepartureDate, obj.FromCity, obj.ToCity, obj.PaidAmount, obj.TicketType, obj
  • 防止在自动生成的GridView列中进行HTML编码(Prevent HTML encoding in auto-generated GridView columns)
    问题 我有一个绑定到我构造的DataTable的GridView。 表中的大多数列都包含用于hypelinklink的原始HTML,我希望将该HTML呈现为浏览器中的链接,但是GridView会自动对HTML进行编码,因此将其呈现为标记。 在没有显式添加HyperLink或任何其他列的情况下,如何避免这种情况? 回答1 只需将BoundColumn.HtmlEncode属性设置为false: <asp:BoundField DataField="HtmlLink" HtmlEncode="false" /> 恐怕没有简单的方法可以使用AutoGenerateColumns = true禁用GridView内容的HTML编码。 但是,我可以想到两种解决方法,它们可以解决您面临的问题: 选项1:在执行基本方法之前,继承GridView类,重写Render方法,遍历所有单元格,对其内容进行解码: for (int i = 0; i < Rows.Count; i++) { for (int j = 0; j < Rows[i].Cells.Count; j++) { string encoded = Rows[i].Cells[j].Text; Rows[i].Cells[j].Text = Context.Server.HtmlDecode(encoded); } } 选项2
  • 使用ASP.NET MVC 4 C#将数据导出到Excel文件正在呈现到视图中(Export data to Excel file with ASP.NET MVC 4 C# is rendering into view)
    问题 我无法将数据导出到Excel。 以下内容似乎将gridview呈现到我的视图中,而不是提示用户使用我已经安装在计算机上的Excel打开。 Public ActionResult ExportToExcel() { var products = this.Repository.Products.ToList(); var grid = new GridView(); grid.DataSource = from p in products select new { Id = p.Id, Name = p.Name }; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response
  • 使用 c# asp.net 增加数据库中的列值(Increment Column Value in database using c# asp.net)
    问题 下面给出了如何在我的数据库文件代码中增加 totaldownloads 值 SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()); SqlCommand sqlcmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); DataTable dt = new DataTable(); DataRow dr; protected void Page_Load(object sender, EventArgs e) { if (Session["UserId"] == null) { lblMessage.Visible = true; GridView1.Visible = false; //AppContent.Visible = false; } else { if (!Page.IsPostBack) { SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString()); ArrayList myArrayList =