The DataGridView class is huge and complex.
It is a beast I'm still struggling with, but once you learn to comprehend it, I find it most rewarding!
Some try to circumvent it by using listboxes and the lot.
Why don't get your feet wet with this as basic as it could get code!
Start a WindowsFormApp, drop in a DataGridView and a Button control.
Fill in the code where needed.
Have fun!
Basic DataGridView
kvprajapati commented: Unbound datagridview. Good snip :) +11
Momerath commented: This is one control I've been avoiding :) +2
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 BasicGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitDataGridView();
}
private void InitDataGridView()
{
//initialize different fields of our object
//see also in the designer.cs file
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "Item";
dataGridView1.Columns[1].Name = "Price";
dataGridView1.Columns[2].Name = "Amount";
dataGridView1.Columns[3].Name = "Total";
// allow selectio of just one cell
dataGridView1.MultiSelect = false;
// show insertion point on entering a cell
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
// set other properties here
}
private void button1_Click(object sender, EventArgs e)
{
// all this is by no means "waterproof" but just doing basic
// get some values from the grid, do a calculation and put the result back
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
double unitprice = Convert.ToDouble(dataGridView1[1, row].Value);
double amount = Convert.ToDouble(dataGridView1[2, row].Value);
double total = unitprice * amount;
dataGridView1.Rows[row].Cells[3].Value = total.ToString();
dataGridView1[3, row].Value = total.ToString();
}
}
}
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.