Click here to Skip to main content
15,886,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I new to programming and need help with selecting dataGridView and checking first column. When I click on "checkBox1" (select all) want to select all cells (rows) and to check all checkBox in dataGrid in columns "No", for now code just select rows without checking them.

input file looks something like:

900006724 00000090000698511 SAVSKI IVАN SREMSKA 101
900007054 000000ZU900006931 SAVSKI JOVАNOVIĆ 29.NOVEMBRA 504
900009856 000000Ih900009856 NOVI IVАN 29.NOVEMBRA 403

and code:
C#
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;
using System.IO;

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

        private void btnload_Click(object sender, EventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.ShowDialog();
            textBox1.Text = of.FileName;
            dataGridView1.DataSource = Class1.LoadUserListFromFile(textBox1.Text);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
           dataGridView1.SelectAll();
           checkBox2.Checked = false;
           checkBox1.Checked = !checkBox2.Checked;
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            dataGridView1.ClearSelection();
            checkBox1.Checked = false;
            checkBox2.Checked=!checkBox1.Checked;
        }

        public class Class1
        {
            public bool No { get; set; }
            public string Id { get; set; }
            public string Sity { get; set; }
            public string Surname { get; set; }
            public string Name { get; set; }
            public string Street { get; set; }
            public string PostalNo { get; set; }
            public string Sity1 { get; set; }
            public string Date { get; set; }
            public string CardDate { get; set; }
            public string PU { get; set; }
            public string Password { get; set; }
            public string IdentificationNo { get; set; }

            public static List<Class1> LoadUserListFromFile(string path)
            {
                var users = new List<Class1>();

                foreach (var line in File.ReadAllLines(path))
                {
                    var columns = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    users.Add(new Class1
                    {
                        No = false,
                        Id = line.Substring(22, 12).Trim(),
                        Sity = line.Substring(48, 20).Trim(),
                        Surname = line.Substring(81, 32).Trim(),
                        Name = line.Substring(113, 36).Trim(),
                        Street = line.Substring(177, 24).Trim(),
                        PostalNo = line.Substring(241, 9).Trim(),
                        Sity1 = line.Substring(263, 20).Trim(),
                        Date = line.Substring(343, 12).Trim(),
                        CardDate = line.Substring(570, 17).Trim(),
                        PU = line.Substring(614, 25).Trim(),
                        Password = line.Substring(694, 10).Trim(),
                        IdentificationNo = line.Substring(710, 13).Trim(),
                    });
                }

                return users;
            }

            public static string input { get; set; }
            public static string[] delimiters { get; set; }
        }
    }
}
Posted
Comments
gggustafson 1-Feb-15 12:20pm    
Provide a real example of the input file. As you have shown it, your SubString statements will return junk. According to those statements, your input record will be 723 characters long - not at all like what you have shown.

An aside. Use RadioButtons in a GroupBox. Then you do not need things like

checkBox2.Checked=!checkBox1.Checked
Member 11383935 1-Feb-15 13:19pm    
Thank you for your response,
something is wrong with the formatting files (or i do not understand how to do it :) ), so I upload it here
http://s000.tinyupload.com/index.php?file_id=00660439883757172149
gggustafson 1-Feb-15 23:49pm    
I will look at your code with the new data you supplied. Bear with me.
gggustafson 2-Feb-15 17:32pm    
See my solution, below.
Member 11383935 3-Feb-15 11:23am    
Thanks, i didn't expect that you will write entire code.
I just added few lines and now it works perfectly. Thanks to you
now i can continue with rest of the code.


In LoadUserListFromFile, because you are extracting data by absolute location (that is Substring), you do not need columns. You also do not need delimiters. From what I can tell (using Head from ViewFile and Head Tools[^], there is no delimiter in the data. So LoadUserListFromFile need only read the data and extract the individual pieces using Substring.



The DataGridView SelectAll and ClearAll do not do what you want them to do. You must add methods to check and uncheck the checkboxes in each row.



We have significantly different styles. The code that I provide exceeds the guidelines that I published in Minimalist Coding Guidelines[^]



I have placed a project in
www.codeproject.com/script/Membership/Uploads/3987831/DataGridSelection.zip
that I hope will help.

 
Share this answer
 
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace DataGridSelection
{

// *************************************** class DataGridSelection

public partial class DataGridSelection : Form
{

// ******************************************* class variables

List<string> checked_rows = new List<string>();


// ******************************************** initialize_GUI

void initialize_GUI()
{

load_BUT.Visible = true;
filename_TB.Visible = true;
filename_TB.Text = "Click Load to choose a file";
users_DGV.SelectionMode =
DataGridViewSelectionMode.FullRowSelect;
users_DGV.Visible = false;
select_deselect_GB.Visible = false;
clear_all_RB.Visible = true;
select_all_RB.Visible = true;
checked_rows_LAB.Visible = false;
checked_rows_TB.Visible = false;
exit_BUT.Visible = true;
}

// ***************************************** DataGridSelection

public DataGridSelection()
{

InitializeComponent();

initialize_GUI();
}

// ******************************************** load_BUT_Click
bool IsHeaderCheckBoxClicked = false; /////////////////// added this

void load_BUT_Click(object sender,
EventArgs e)
{
DialogResult dialog_result;
OpenFileDialog open_file_dialog;

open_file_dialog = new OpenFileDialog();
dialog_result = open_file_dialog.ShowDialog();
if (dialog_result == DialogResult.OK)
{
string filename;

filename = open_file_dialog.FileName;
if (String.IsNullOrEmpty(filename))
{
filename_TB.Text = "A file name must be chosen";
filename_TB.Visible = true;
users_DGV.Visible = false;
select_deselect_GB.Visible = false;
}
else
{
filename_TB.Text = filename;
users_DGV.DataSource = load_users_from_file(
filename);
clear_all();
users_DGV.Visible = true;
select_deselect_GB.Visible = true;
clear_all_RB.Checked = true;
checked_rows_LAB.Visible = true;
checked_rows_TB.Text = String.Empty;
checked_rows_TB.Visible = true;
}
}
else
{
filename_TB.Text = "A file name must be chosen";
filename_TB.Visible = true;
users_DGV.Visible = false;
select_deselect_GB.Visible = false;
}
}

// ***************************************** RB_CheckedChanged

void RB_CheckedChanged(object sender,
EventArgs e)
{

bool is_checked = false;
RadioButton radio_button = (RadioButton)sender;
string tag = radio_button.Tag.ToString().
ToLower().
Trim();

is_checked = radio_button.Checked;
switch (tag)
{
case "select_all":
select_all();
break;

case "clear_all":
clear_all();
break;

default:
throw new ApplicationException(
String.Format(
"{0} is an unrecognized RadioButton tag",
radio_button.Tag.ToString()));
}
}

// ************************************************ select_all

void select_all()
{

foreach (DataGridViewRow row in users_DGV.Rows)
{
DataGridViewCheckBoxCell check_box_cell;

check_box_cell =
(DataGridViewCheckBoxCell)row.Cells[0];

check_box_cell.Value = true;

}
users_DGV.SelectAll(); ////////// added this
}

// ************************************************* clear_all

void clear_all()
{

foreach (DataGridViewRow row in users_DGV.Rows)
{
DataGridViewCheckBoxCell check_box_cell;

check_box_cell =
(DataGridViewCheckBoxCell)row.Cells[0];

check_box_cell.Value = false;
}
users_DGV.ClearSelection(); ////////// added this
}

// ********************************** load_users_from_file

List<userdata> load_users_from_file(string path)
{
List<userdata> users = new List<userdata>();

foreach (string line in File.ReadAllLines(path))
{
users.Add(new UserData
{
No = true,
Id = line.Substring(22, 12).Trim(),
Sity = line.Substring(48, 20).Trim(),
Surname = line.Substring(81, 32).Trim(),
Name = line.Substring(113, 36).Trim(),
Street = line.Substring(177, 24).Trim(),
PostalNo = line.Substring(241, 9).Trim(),
Sity1 = line.Substring(263, 20).Trim(),
Date = line.Substring(343, 12).Trim(),
CardDate = line.Substring(570, 17).Trim(),
PU = line.Substring(614, 25).Trim(),
Password = line.Substring(694, 10).Trim(),
IdentificationNo = line.Substring(710, 13).
Trim(),
});
}

return (users);
}

// ******************************************** exit_BUT_Click

void exit_BUT_Click(object sender,
EventArgs e)
{

Application.Exit();
}

// ******************** users_DGV_CurrentCellDirtyStateChanged

void users_DGV_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
{

if (users_DGV.IsCurrentCellDirty)
{
users_DGV.CommitEdit(
DataGridViewDataErrorContexts.Commit);
}
}

// ******************************** users_DGV_CellValueChanged


private void No(CheckBox HCheckBox) //////////////////////////// added this
{
IsHeaderCheckBoxClicked = true; /////////////////////////// added this
}

void users_DGV_CellValueChanged(
object sender,
DataGridViewCellEventArgs e)
{
if (!IsHeaderCheckBoxClicked) /////////////////////// added this
RowCheckBoxClick(); ////////////////////// added this

int index = e.RowIndex;
checked_rows_TB.Text = String.Empty;

if (e.ColumnIndex == 0)
{
DataGridViewCheckBoxCell check_box_cell;
DataGridViewRow row;

row = users_DGV.Rows[index];
check_box_cell =
(DataGridViewCheckBoxCell)row.Cells[0];
if ((bool)check_box_cell.Value)
{
checked_rows.Add(index.ToString());
}
else if (checked_rows.Contains(
index.ToString()))
{
checked_rows.Remove(index.ToString());

}
}

checked_rows.Sort();


foreach (string checked_row in checked_rows)
{
checked_rows_TB.Text += checked_row + " ";

}
}






// class DataGridSelection

// ************************************************ class UserData

public class UserData
{

public bool No { get; set; }
public string Id { get; set; }
public string Sity { get; set; }
public string Surname { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string PostalNo { get; set; }
public string Sity1 { get; set; }
public string Date { get; set; }
public string CardDate { get; set; }
public string PU { get; set; }
public string Password { get; set; }
public string IdentificationNo { get; set; }



}


private void dgvSelectAll_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (!IsHeaderCheckBoxClicked) ////////// added this

RowCheckBoxClick(); ////////// added this
}

private void RowCheckBoxClick()
{
foreach (DataGridViewRow Row in users_DGV.Rows)
{
if ((bool)(Row.Cells["No"].Value) == true)
{
this.users_DGV.Rows[Row.Index].Selected = true;
}
else
{
this.users_DGV.Rows[Row.Index].Selected = false;
}
}

}
}
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900