I am new to WinForms and am trying to make an application that will hold certain data in a DataGridView Style.
Now I've managed to create the app where if clicked on a cell the TextBoxes and the ComboBox get populated with data from the GridView, but I am now struggling to get the DateTimePicker to do the same...
Bellow you will see the code I am using to call the data back into the text and combo boxes, but I am missing the proper call for the DateTimePicker and I don't know how to call it properly
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
index = e.RowIndex;
DataGridViewRow row = dataGridView1.Rows[index];
textBox1.Text = row.Cells[0].Value.ToString();
dateTimePicker1.Value = row.Cells[1].Value.ToString();
comboBox1.Text = row.Cells[2].Value.ToString();
textBox2.Text = row.Cells[3].Value.ToString();
}
I am aware I can't convert type string to System.DateTime, but I don't know how I can do that...
Thank you in advance.
CodePudding user response:
If you'd like to try this approach, make a class to represent a Row
in the view.
class Record
{
public string Description { get; set; } = $"Item {autoName }";
public DateTime Date { get; set; } = DateTime.Now;
public CBValues Value { get; set; } = CBValues.Apple;
static char autoName = 'A';
}
enum CBValues
{
Apple,
Orange,
Banana,
}
Next make a BindingList<Record>
of them...
BindingList<Record> Records = new BindingList<Record>();
and set it as the DataSource
of your DataGridView
in this initialization method which also installs the custom columns (the CalendarColumn
class is copied from this Microsoft sample).
private void InitializeDataGridView()
{
dataGridView1.AllowUserToAddRows = false;
// Bind the list of records to the DataGridView
dataGridView1.DataSource = Records;
// Add one or more records to autogenerate the Columns
for (int i = 0; i < 3; i ) Records.Add(new Record());
// Swap autogenerated column for CalendarColumn.
dataGridView1.Columns.Remove(dataGridView1.Columns[nameof(Record.Date)]);
dataGridView1.Columns.Add(
// This class is copied from Microsoft example.
new CalendarColumn
{
Name = nameof(Record.Date),
DataPropertyName = nameof(Record.Date),
});
// Swap autogenerated column so DataGridViewComboboxColumn.
dataGridView1.Columns.Remove(dataGridView1.Columns[nameof(Record.Value)]);
dataGridView1.Columns.Add(
new DataGridViewComboBoxColumn
{
Name = nameof(Record.Value),
DataPropertyName = nameof(Record.Value),
DataSource = Enum.GetValues(typeof(CBValues)),
});
// Format columns
dataGridView1.Columns[nameof(Record.Description)].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns[nameof(Record.Date)].Width = 150;
}