I’m trying to get “firstName, lastName, assocID, etc.” to display in a datagrid on my form. I’m a new programmer/script kiddie, sorry if this is a dumb question. I just don’t know how to call associateList.firstName to a readable datagrid entry.
I would like the datagrid to use every associate in associateList if possible. Was considering a basic counter on an index refrence somehow.
Other input on how I’m writing my code is appreciated as well. I’m new, and self-taught.
In short : I want the associates to display in the datagrid using columns to separate the information.
The datagrid name is dataGridAssociates on the windows form.
namespace Associate_Tracker
{
public partial class Form1 : Form
{
public class Associate
{
//No idea wtf {get; set;} does but I read that I need it?
public string firstName { get; set; }
public string lastName { get; set; }
public string assocRFID { get; set; }
public int assocID { get; set; }
public bool canDoDiverts { get; set; }
public bool canDoMHE { get; set; }
public bool canDoLoading { get; set; }
}
public Form1()
{
InitializeComponent();
}
private void buttonAddAssoc_Click(object sender, EventArgs e)
{
#region Datagrid Creation -- Name: dt
DataTable dt = new DataTable();
dt.Columns.Add("First Name");
dt.Columns.Add("Last Name");
dt.Columns.Add("RFID");
dt.Columns.Add("Associate ID#");
dt.Columns.Add("Diverts");
dt.Columns.Add("MHE");
dt.Columns.Add("Loading");
dataGridAssociates.DataSource = dt;
#endregion
//First & Last name splitter
string allValue = textBoxAssocName.Text;
string firstNameTemp = String.Empty;
string lastNameTemp = String.Empty;
int getIndexOfSpace = allValue.IndexOf(' ');
for (int i = 0; i < allValue.Length; i++)
{
if (i < getIndexOfSpace)
{
firstNameTemp += allValue[i];
}
else if (i > getIndexOfSpace)
{
lastNameTemp += allValue[i];
}
}
firstNameTemp = firstNameTemp.Trim(); // To remove empty spaces
lastNameTemp = lastNameTemp.Trim(); // To Remove Empty spaces
//End splitter
int assocIDTemp; //TryParse succeeds
bool assocIDparse; //Bool for TryParse
//Try Parsing Associate ID to an integer
//Includes catch -> return
assocIDparse = int.TryParse(textBoxAssocID.Text, out assocIDTemp);
if (assocIDparse == false)
{
MessageBox.Show("Please use only numbers in the AssocID input");
return;
}
var associateList = new List<Associate>();
associateList.Add(new Associate
{
firstName = firstNameTemp,
lastName = lastNameTemp,
assocID = assocIDTemp,
canDoDiverts = checkBoxDiverts.Checked,
canDoMHE = checkBoxMHE.Checked,
canDoLoading = checkBoxLoading.Checked,
});
textBoxAssocID.Clear();
textBoxAssocName.Clear();
textBoxRFID.Clear();
}
}
}
I won’t say that this is the most elegant way of doing this but with WinForms and DataGridView control you can use the BindingSource control to do this. I have added a sample below with the modified code to achieve what you are trying to do.
The key points to note here are as follow:
Any problem let me know.