Kapil Dahal
Kapil Dahal

Reputation: 1

Error when using dataGridView

I have to show dataGridView1 as

SN    Name        Subject       Topic            Subtopic
1.    Mr.SK Jha   Physics       Optics           Diffraction
                                                 Interference
                                Mechanics        MKS
                                Electromagnetic
2.    Mr.XYZ     Chemistry      Inorganic        Ethene

Here the topic is the same from subject_id and it may have many data not specified as fixed.

I have seen many reference but it gives GridViewRow as error.

I am using Visual Studio 2013, framework 4.5

Upvotes: 0

Views: 77

Answers (2)

jdweng
jdweng

Reputation: 34433

Easiest method is to make the datasource a datatable

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable();
            dt.Columns.Add("SN", typeof(string));
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Subject", typeof(string));
            dt.Columns.Add("Topic", typeof(string));
            dt.Columns.Add("Subtopic", typeof(string));

            dt.Rows.Add(new object[] { "1.", "Mr.SK Jha", "Physics", "Optics", "Diffraction Interference" });
            dt.Rows.Add(new object[] { "", "", "", "Mechanics", "MKS" });
            dt.Rows.Add(new object[] { "", "", "", "Electromagnetic" });
            dt.Rows.Add(new object[] { 2, "Mr.XYZ", "Chemistry", "Inorganic", "Ethene" });

            dataGridView1.DataSource = dt;
        }
    }
}
​

Upvotes: 2

TaW
TaW

Reputation: 54453

I assume that you want the DGV to look like a grouped table, with the repeating values suppressed.

This is a routine to paint the repeating cells transparent:

static void PaintGrouped(DataGridView dgv)
{
    if (dgv.Rows.Count < 2) return;
    if (dgv.Columns.Count < 2) return;
    for (int row = 1; row < dgv.Rows.Count; row++)
    {
        bool suppressing = dgv[0, row].Value.Equals(dgv[0, row - 1].Value);
        for (int col = 1; col < dgv.Columns.Count; col++)
        {
            bool equal = dgv[col, row].Value.Equals(dgv[col, row - 1].Value);
            suppressing = suppressing && equal;
            dgv[col, row].Style.ForeColor = supressing ? Color.Transparent : Color.Black;
        }
    }
}

Note that all values are still in place and be changed or copied. After any changes you should re-apply the routine! Also note that I have decided to never suppress the 1st column.

Upvotes: 1

Related Questions