Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WPF
I am using datagrid view in wpf application.
 
Dataview is bound with datatable and column having same value are merged. i have used onPaint method . Every thing is working fine but there is one problem the content of second merged column is shown on header
 

here is my code
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Windows.Forms;
using System.Drawing;
 
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window2.xaml
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
            
            dataGrid.Paint += new PaintEventHandler(dataGrid_Paint);
 
            btnOk.IsDefault = true;
            btnCancel.IsCancel = true;
 
            Loaded += new RoutedEventHandler(Window2_Loaded);
         
        }
 
        void dataGrid_Paint(object sender, PaintEventArgs e)
        {
            dataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            Merge();
            
        }
 
        DataSet dataSet = new DataSet();
        DataSet dataSet1 = new DataSet();
        private List<string> MergedRowsInFirstColumn = new List<string>();
 
        void Window2_Loaded(object sender, RoutedEventArgs e)
        {
            DataTable tbl_main = new DataTable("tbl_main");
            tbl_main.Columns.Add("SubGroup");
            tbl_main.Columns.Add("PartName");
            tbl_main.Columns.Add("PartLib");
 
            DataRow dr = tbl_main.NewRow();
            dr[0] = "Test";
            dr[1] = "Part15";
            dr[2] = "Lib1";
            tbl_main.Rows.Add(dr);
 
            dr = tbl_main.NewRow();
            dr[0] = "Test";
            dr[1] = "Part2";
            dr[2] = "Lib2";
            tbl_main.Rows.Add(dr);
 
            dr = tbl_main.NewRow();
            dr[0] = "Test";
            dr[1] = "Part2";
            dr[2] = "Lib2";
            tbl_main.Rows.Add(dr);
 
            dr = tbl_main.NewRow();
            dr[0] = "Test1";
            dr[1] = "Part3";
            dr[2] = "Lib2";
            tbl_main.Rows.Add(dr);
        
 
            dr = tbl_main.NewRow();
            dr[0] = "Test1";
            dr[1] = "Part1";
            dr[2] = "Lib1";
            tbl_main.Rows.Add(dr);
 
            dataSet1.Tables.Add(tbl_main);
            dataSet1.Tables[0].DefaultView.Sort = "SubGroup ASC";
            dataSet.Tables.Add(dataSet1.Tables[0].DefaultView.ToTable());
            dataGrid.DataSource = dataSet;
            dataGrid.DataMember = "tbl_main";
            
            //dataGrid.Rows.RemoveAt(dataGrid.Rows.Count - 1);
            dataGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
 
            dataGrid.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            //long height = 0;
            //for (int i = 0; i < dataGrid.Rows.Count; i++)
            //    height += dataGrid.Rows[i].Height;
            //wfh.Height = dataGrid.ColumnHeadersHeight + height+2;
            
        }
 

        private void Merge()
        {
            int[] RowsToMerge = new int[3];
            RowsToMerge[0] = -1;
            int rowcount = dataGrid.HorizontalScrollingOffset / 11;
            //Merge first column at first
            for (int i = 0; i < dataSet.Tables["tbl_main"].Rows.Count - 1; i++)
            {
                if (dataSet.Tables["tbl_main"].Rows[i]["SubGroup"] == dataSet.Tables["tbl_main"].Rows[i + 1]["SubGroup"])
                {
                    if (RowsToMerge[0] == -1)
                    {
                        RowsToMerge[0] = i;
                        RowsToMerge[1] = i + 1;
                    }
                    else
                    {
                        RowsToMerge[1] = i + 1;
                    }
                }
                else
                {
                    if (RowsToMerge[0] != -1)
                    {
                        MergeCells(RowsToMerge[0], RowsToMerge[1], dataGrid.Columns["SubGroup"].Index,  false);
                        CollectMergedRowsInFirstColumn(RowsToMerge[0], RowsToMerge[1]);
                        RowsToMerge[0] = -1;
                    }
                }
                //if (i == dataSet.Tables["tbl_main"].Rows.Count - 2 )
                //{
                //    MergeCells(i + 1, i + 1, dataGrid.Columns["SubGroup"].Index, isSelectedCell(RowsToMerge, dataGrid.Columns["SubGroup"].Index) ? true : false);
                //    CollectMergedRowsInFirstColumn(RowsToMerge[0], RowsToMerge[1]);
                //    RowsToMerge[0] = -1;
                //}
            }
            if (RowsToMerge[0] != -1)
            {
                MergeCells(RowsToMerge[0], RowsToMerge[1], dataGrid.Columns["SubGroup"].Index,false);
                RowsToMerge[0] = -1;
            }
 
            //merge all other columns
            //for (int iColumn = 1; iColumn < dataSet.Tables["tbl_main"].Columns.Count - 1; iColumn++)
            //{
            //    for (int iRow = 0; iRow < dataSet.Tables["tbl_main"].Rows.Count - 1; iRow++)
            //    {
            //        if ((dataSet.Tables["tbl_main"].Rows[iRow][iColumn] == dataSet.Tables["tbl_main"].Rows[iRow + 1][iColumn]) &&
            //             (isRowsHaveOneCellInFirstColumn(iRow, iRow + 1)))
            //        {
            //            if (RowsToMerge[0] == -1)
            //            {
            //                RowsToMerge[0] = iRow;
            //                RowsToMerge[1] = iRow + 1;
            //            }
            //            else
            //            {
            //                RowsToMerge[1] = iRow + 1;
            //            }
            //        }
            //        else
            //        {
            //            if (RowsToMerge[0] != -1)
            //            {
            //                MergeCells(RowsToMerge[0], RowsToMerge[1], iColumn, isSelectedCell(RowsToMerge, iColumn) ? true : false);
            //                RowsToMerge[0] = -1;
            //            }
            //        }
            //    }
            //    if (RowsToMerge[0] != -1)
            //    {
            //        MergeCells(RowsToMerge[0], RowsToMerge[1], iColumn, isSelectedCell(RowsToMerge, iColumn) ? true : false);
            //        RowsToMerge[0] = -1;
            //    }
            //}
           
        }
 
        private bool isRowsHaveOneCellInFirstColumn(int RowId1, int RowId2)
        {
 
            foreach (string rowsCollection in MergedRowsInFirstColumn)
            {
                string[] RowsNumber = rowsCollection.Split(';');
 
                if ((isStringInArray(RowsNumber, RowId1.ToString())) &&
                    (isStringInArray(RowsNumber, RowId2.ToString())))
                {
                    return true;
                }
            }
            return false;
        }
 
        private bool isStringInArray(string[] Array, string value)
        {
            foreach (string item in Array)
            {
                if (item == value)
                {
                    return true;
                }
 
            }
            return false;
        }
 
        private void CollectMergedRowsInFirstColumn(int RowId1, int RowId2)
        {
            string MergedRows = String.Empty;
 
            for (int i = RowId1; i <= RowId2; i++)
            {
                MergedRows += i.ToString() + ";";
            }
            MergedRowsInFirstColumn.Add(MergedRows.Remove(MergedRows.Length - 1, 1));
        }
 
        private void MergeCells(int RowId1, int RowId2, int Column, bool isSelected)
        {
            int height1=dataGrid.Rows[0].Height;
            if (RowId1 == 0)
            {
                if (dataGrid.VerticalScrollingOffset == 0)
                    RowId1 = 0;
                else
                {
                    if ((dataGrid.VerticalScrollingOffset / height1) == 0)
                        RowId1 = 0;
                    else if ((dataGrid.VerticalScrollingOffset / height1) != 0 && (dataGrid.VerticalScrollingOffset % height1 == 0))
                        RowId1 = dataGrid.VerticalScrollingOffset / height1;
                    else
                        RowId1 = (dataGrid.VerticalScrollingOffset / height1) + 1;
                }
            }
            Graphics g = dataGrid.CreateGraphics();
            System.Drawing.Pen gridPen = new System.Drawing.Pen(dataGrid.GridColor);
 
            //Cells Rectangles
            System.Drawing.Rectangle CellRectangle1 = dataGrid.GetCellDisplayRectangle(Column, RowId1, true);
            System.Drawing.Rectangle CellRectangle2 = dataGrid.GetCellDisplayRectangle(Column, RowId2, true);
 
            int rectHeight = 0;
            string MergedRows = String.Empty;
 
            for (int i = RowId1; i <= RowId2; i++)
            {
                rectHeight += dataGrid.GetCellDisplayRectangle(Column, i, false).Height;
            }
            
            System.Drawing.Rectangle newCell = new System.Drawing.Rectangle(CellRectangle1.X, CellRectangle1.Y, (CellRectangle1.Width-2), (rectHeight-1));
 
            g.FillRectangle(new SolidBrush(isSelected ? dataGrid.DefaultCellStyle.SelectionBackColor : dataGrid.DefaultCellStyle.BackColor), newCell);
 
            g.DrawRectangle(gridPen, newCell);
 
            g.DrawString(dataGrid.Rows[RowId1].Cells[Column].Value.ToString(), dataGrid.DefaultCellStyle.Font, new SolidBrush(isSelected ? dataGrid.DefaultCellStyle.SelectionForeColor : dataGrid.DefaultCellStyle.ForeColor), newCell.X + newCell.Width / 3, newCell.Y + newCell.Height / 3);
           
        }
 
        private bool isSelectedCell(int[] Rows, int ColumnIndex)
        {
            if (dataGrid.SelectedCells.Count > 0)
            {
                for (int iCell = Rows[0]; iCell <= Rows[1]; iCell++)
                {
                    for (int iSelCell = 0; iSelCell < dataGrid.SelectedCells.Count; iSelCell++)
                    {
                        if (dataGrid.Rows[iCell].Cells[ColumnIndex] == dataGrid.SelectedCells[iSelCell])
                        {
                            return true;
                        }
                    }
                }
                return false;
            }
            else
            {
                return false;
            }
        }
 
        private void btnOk_Click(object sender, EventArgs e)
        {
            Close();
        }
 
        private void btnCancel_Click(object sender, EventArgs e)
        {
 
        }
    }
}
 
and xaml file is
 

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:swf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="Window2" Height="400" Width="500"
SizeToContent="Height"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize">






 

<Image Name="imgInformation" ></Image>
<Label Content="This is Test"/>





x:Name="dataGrid"
AutoGenerateColumns="False"
AllowUserToAddRows="False"
RowHeadersVisible="False"
SelectionMode="ColumnHeaderSelect"
AutoSize="True">









<Button Name="btnOk" Height="25" Width="80" Margin="10,20,10,20" VerticalAlignment="Top" Content="OK" Click="btnOk_Click" />
<Button Name="btnCancel" Height="25" Width="80" Margin="10,20,20,20" VerticalAlignment="Top" Content="Cancel" Click="btnCancel_Click"/>


 

 

 

Please help
Posted 11-Jul-13 10:43am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Richard MacCutchan 269
1 Aajmot Sk 252
2 Marcin Kozub 235
3 Sergey Alexandrovich Kryukov 185
4 Praneet Nadkar 167
0 OriginalGriff 7,913
1 Sergey Alexandrovich Kryukov 7,232
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,865


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 11 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100