C# DataGridView and Input Form - c#

I have a DataGridView binded with data from a database. I need to create a Form, which has input fields for data from a single grid row.
The Form has 30+ input controls - TextBoxes, Checkboxes and NumericUpDowns.
For now I went with this approach:
Retrieve current row from the DataGridView and load values from the cells to class instance
Pass the instance to the form and manually fill the input controls
Update the database from the form, update the DataGridView
I want to improve some things:
Is there any way to quickly fill all input controls from a class instance?
Is there any way to determine which input controls have changed their values besides manually subscribing every control on an event handler?
Is there any way to improve this whole thing, e.g. do something more efficiently?

If you are already passing in a DataRow, then you could instead pass in the DataTable and something that identifies the row in that table. And maybe optionally an adapter, if you want to commit the changes immediately on form exit. Then you can create a DataView of that table. And bind each edit control to a field in that view. Something like this:
public partial class EditForm : Form
{
DataRow row = null;
DataView view;
SqlDataAdapter adapter;
public EditForm(SqlDataAdapter adapter, DataTable table, int rowId)
{
InitializeComponent();
this.adapter = adapter;
view = table.DefaultView;
view.RowFilter = $"ID = {rowId}";
if (view.Count == 0) throw new Exception("no such row");
DataRowView dvr = view[0];
row = dvr.Row;
datebox.DataBindings.Add(new Binding("Value", view, "DATE"));
stringbox.DataBindings.Add(new Binding("Text", view, "O_STRING"));
this.FormClosing += EditForm_FormClosing;
}
private void EditForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (row.RowState == DataRowState.Modified) adapter.Update(new DataRow[] { row });
}
}
The above assuming that your table has key column named ID and fields DATE and O_STRING.
This will save you the trouble of creating an intermediate custom class instance, based on that row, moving values to and from various objects and automatically sets the RowStatae in the original table.

Re: value changed indicators. Not sure if there is a really elegant way to do that. Firstly, if I had to, I would change the background (or foreground) color rather than font boldness. Setting font to bold would change the width of the content and that is usually quite annoying. Then, I would add handlers to the TextChanged events (or ValueChange events, for controls that are not text-based). You dont need to write custom handlers to each and every edit control - in the event handler, you get the object sender parameter that points to the control object. Then you can get the field name binded to that control with something like this:
private void stringbox_TextChanged(object sender, EventArgs e)
{
Control ctrl = (Control)sender;
string fieldName = ctrl.DataBindings[0].BindingMemberInfo.BindingMember;
if ((string)view[0].Row[fieldName] != ctrl.Text) ctrl.BackColor = Color.Pink;
}
That way you will only need to add a TextChanged handler once (per edit contol class), not one per every edit box you have.

Related

WinForm - DataGridView when row change event

I currently have an event set for RowHeaderMouseClick when I click on the header, my textbox is populated with data from the DataGrid. I want to make my textbox populate when I select the row instead of the header. Ideally, I want to hide the header. What is the correct event/property that I need to set to achieve this?
Edit:
Attaching screenshot
You can make like this for any event
//Handle RowChanged.
table.RowChanged += table_RowChanged;
//RowChanged Event.
static void table_RowChanged(object sender, DataRowChangeEventArgs e)
{
Console.WriteLine("... Changed: " + (int)e.Row["Dosage"]);
}
You don't need to do it with events, as you seem to be saying that the textbox gets populated with an item from the row. In such a case you would have:
your datagridview bound to a bindingsource
your bindingsource bound to a datatable or other list that supports binding
your textbox's text property bound to the same bindingsource
Every time the user clicks a row in the grid (or uses the keyboard to move to another row) they are causing the Current property of the bindingsource to update. This in turn changes any of the textboxes that are bound to true same binding source (a textbox only shows the current row item to which it is bound)
For a quick demo of how this works, do these steps (apologies I can't make any screenshots - I'm on a cellphone) - skip any steps you've already done
add a DataSet type file to your project
open it and right click the surface, add a datatable and name it eg Person
right click it and add a couple of columns eg FirstName and LastName
save
switch to the form
open the Dat Sources window (view menu, other windows)
drag the Person node to the form, a datagridview appears as well as some other stuff (bindingsource) - look at the DataSource property of the grid
in the Data sources window again click the drop down button next to Person, change it to details
drag the person node to the form again, this time textboxes appear; take a look at their Text bindings in the (data bindings) section of their properties - they're bound to the same bindingsource as the grid is
run the project, type 4 names into the grid and then select different rows at random using the mouse; the textboxes update to stay current with the grid selection
If this isn't the way you've done things up to now you should consider making it the way; using the DataSet designer to create strongly typed datatables is an easy way to model the data aspects of your program and there is a lot of tooling set up to make life easier when you use them to make a data driven app. If you've been putting data directly into a datagridview it's something you should avoid going forward, and instead separate your concerns in a more mvc style pattern
If you want to remove or make the rowHeader invisible
You can SET an Event DataGridView CellClick and below is the CODE
//Im Assuming that we are getting the row VALUES
try{
int rowIndex = e.RowIndex; //getting the position of ROW in DGV when CLick
int columns = Columns.Count//numebr of Columns
for(int i=0; i< columns;i++)
{
//Here we can populate textBoxes and using FlowLayoutPanel
string values = dataGridView1.Rows[rowIndex].Columns[i].Value.toString();
//Creating new TextBox
TextBox txtBox = new TextBox();
txtBox.Text = values;
txtBox.Size = new Size(100,200);
flowLayoutPanel1.Controls.Add(txtBox);
}
}catch(Exception ee){}
OR If you want to pass the VALUES of the selected ROW you can do like this
textBox.Text = dataGridView1.Rows[rowIndex].Columns[0].Value.toString();//1st col
textBox1.Text = dataGridView1.Rows[rowIndex].Columns[1].Value.toString();//2nd col
First, right-click your dataGrid and select properties
Then change the SelectionMode to FullRowSelect if you like as shown below:
Next, In the datagrid event section double-click on SelectionChanged
and write code like this, you can use other events, although
// Just for example
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
try
{
if (dataGridView1.CurrentRow != null && dataGridView1.CurrentRow.Index >= 0)
{
var row = dataGridView1.CurrentRow;
txtCode.Text = (row.Cells["code"].Value != null) ? row.Cells["code"].Value.ToString() : string.Empty;
txtFirstName.Text = (row.Cells["firstName"].Value != null) ? row.Cells["firstName"].Value.ToString() : string.Empty;
txtLastName.Text = (row.Cells["lastName"].Value != null) ? row.Cells["lastName"].Value.ToString() : string.Empty;
}
}
catch { }
}

How Can i Convert datagridview datasource to BindingListView (Equin.ApplicationFramework.BindingListView)

I set this DataBindingComplete event to my datagridview. I want every datasource that binding to datagridview can be sortable by clicking on column.
void MakeColumnsSortable_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView dataGridView = sender as DataGridView;
foreach (DataGridViewColumn column in dataGridView.Columns)
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
all of my datasource is List and bindingsource doesnot sort when my list is ended by .ToList
Now . how can i convert datagridview.datasource to Equin.ApplicationFramework.BindingListView and set it again to datasource for make any datagridview sortable?
Proper usage of Equin.ApplicationFramework.BindingListView would be as follows
Upon creation of your form:
Create a BindingListView. It will be filled later with the items that you want to display / sort / filter
Create a BindingSource.
Create a DataGridView.
Add the columns to the properties you want to show
The latter three steps can be done in visual studio designer. If you do that, The code will be in InitializeComponents.
Suppose you want to show / sort / filter elements of MyType Your form will be like:
public class MyForm : Form
{
private BindingListView<MyType> MyItems {get; set;}
public MyForm()
{
InitializeComponent();
this.MyItems = new BindingListView<MyType>(this.components);
// components is created in InitializeComponents
this.MyBindingSource.DataSource = this.MyItems;
this.MyDataGridView.DataSource = this.MyBindingSource;
// assigning the DataPropertyNames of the columns can be done in the designer,
// however doing it the following way helps you to detect errors at compile time
// instead of at run time
this.columnPropertyA = nameof(MyType.PropertyA);
this.columnPropertyB = nameof(MyType.PropertyB);
...
}
You can do without the BindingSource, you can assign the BindingListViewdirectly to the DataSource of the DataGridView. Sorting and Filtering will still work. However the BindingSource will help you to access the currently selected item.
private MyType SelectedItem
{
get {return ((ObjectView<MyType>)this.MyBindingSource.Current)?.Object; }
}
private void DisplayItems (IEnumerable<MyType> itemsToDisplay)
{
this.MyItems.DataSource = itemsToDisplay.ToList();
this.MyItems.Refresh(); // this will update the DataGridView
}
private IEnumerable<MyType> DisplayedItems
{
get {return this.MyItems; }
// BindingListview<T> implements IEnumerable<T>
}
This is all. You don't need to create special functions to sort on mouse clicks. The sorting will be done automatically inclusive deciding on the sort order and displaying the correct sorting glyphs. If you want to sort programmatically:
// sort columnPropertyA in descending order:
this.MyDataGridView.Sort(this.columnPropertyA.ListsortDirection.Descending);
One of the nice things about the BindingListView is the filtering option:
// show only items where PropertyA not null:
this.MyItems.ApplyFilter(myItem => myItem.PropertyA != null);
// remove the filter:
this.MyItems.RemoveFilter();
(I'm not sure if a Refresh() is needed after applying or removing a filter

Create or generate a control based on database results

How do I create a control in a windows form application? I want to generate a textbox or a radio button when I select something from a Combobox. I basically want to query my database, and based on the values of the fields, I want to generate a textbox or a radio button. For example, if my query returns a value of "Textbox", I want to generate a textbox on the form in a specified location. How does one accomplish this? Please help.
The easiest way is to create the control manually in code and then add it to the Controls collection. Deciding which control to create depending on some input data (whether it's database query or a value selected from a combobox) is not much different then in any other case. Simple if will do the job. For instance:
private void AddControl(string control)
{
if (control == "Textbox")
{
TextBox tb = new TextBox();
tb.Location = new Point(100, 100);
this.Controls.Add(tb);
}
else if (control == "Radio")
{
RadioButton rb = new RadioButton();
rb.Location = new Point(200, 100);
this.Controls.Add(rb);
}
}
Of course, it's very naive version. But it's only a starting point. I leave to you adding more advanced logic (like dynamically adjusting location, setting up properties of the radio button or the textbox, relying on Type instead of on a simple string, etc.)
The assumption is that you retrieve a string value from the database. For example in form's constructor:
public Form1()
{
InitializeComponent();
string requestedControl = QueryDatabase();
AddControl(requestedControl);
}
I leave to you implementing the method to query the database.
In the question you also mentioned adding a control after selecting it in the combobox. In this case the only difference is that you rely on an event triggered after combobox's selection changed:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
string res = this.comboBox1.SelectedItem.ToString();
this.AddControl(res);
}
Here you rely on SelectedValueChanged event. Of course, in this case your combobox has to be populated with expected values (here "Radio" and "Textbox"). Also, you have to attach the event handler to the specific event on the combobox. You can do that in designer or by adding in the constructor the following line:
combobox1.SelectedValueChanged += comboBox1_SelectedValueChanged;
Hope that clarifies the issue and sets up some starting point for you to continue from.

Alternative to DataGridView DataBindingComplete Event

As stated here the DataBindingComplete event for a DataGridView is fired whenever the contents of the data source change, or a property such as DataSource changes. This results in the method being called multiple times.
I am currently using the DataBindingComplete event to do some visual formatting to my form. For example, I make the text in the first column (column 0) appear as Row Headers and then hide that column (see code below).
private void grdComponents_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// do more stuff...
}
It is unnecessary to execute this code more than once, and I am looking to put it into a place where that can happen. Unfortunately it didn't work when I added the snippet to the end of my form's Load method (after I set the DataSource of my DataGridView), nor did it work in the DataSourceChanged event.
Yes, you can use DataSourceChanged event, but be aware, that it occurs only when data source is changed. Additionally, DataBindingComplete offers you information why it has happend - through e.ListChangedType:
Reset = 0,// Much of the list has changed. Any listening controls should refresh all their data from the list.
ItemAdded = 1,// An item added to the list
ItemDeleted = 2,// An item deleted from the list.
ItemMoved = 3,// An item moved within the list.
ItemChanged = 4,// An item changed in the list.
PropertyDescriptorAdded = 5,// A System.ComponentModel.PropertyDescriptor was added, which changed the schema.
PropertyDescriptorDeleted = 6,// A System.ComponentModel.PropertyDescriptor was deleted, which changed the schema.
PropertyDescriptorChanged = 7// A System.ComponentModel.PropertyDescriptor was changed, which changed the schema.
According to this answer:
https://social.msdn.microsoft.com/forums/windows/en-us/50c4f46d-c3b8-4da7-b08f-a751dca12afd/databindingcomplete-event-is-been-called-twice
the whole thing happens because you don't have DataMember property set in your dataGridView. And you can set it only if you want to set particular table from database which is set as your DataSource of dataGridView. Other way - throws an exception.
The simplest way will be just to execute this code once:
Add a flag like Boolean isDataGridFormatted in your form.
And check it like
private void grdComponents_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
if (this.isDataGridFormatted )
return;
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// do more stuff...
this.isDataGridFormatted = false;
}
A bit better will be to prepare your DataGridView during the form construction. As I understand your columns won't change during the course of your program but you don't want to initialize everything manually. You could load some dummy one-item(one-row) data during the initialization:
private void Initialize_DataGridView()
{
// Add dummy data to generate the columns
this.dataGridView_Items.DataContext = new Item[]{ new Item {Id = 5, Value = 6}};
// Make your formatting
foreach (DataGridViewRow row in grdComponents.Rows)
{
row.HeaderCell.Value = row.Cells[0].Value.ToString();
}
grdComponents.Columns[0].Visible = false;
// Reset the dummy data
this.dataGridView_Items.DataContext = null; // Or new Item[]{};
}
...
public MyForm()
{
Initialize();
this.Initialize_DataGridView();
}
I am not sure that exactly such code will work with dataGridView but it is close enough.
Of course an event would have been a nearly ideal solution but there's hardly any that deals with successful autogeneration of columns http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview_events(v=vs.110).aspx except the AutoGenerateColumnChanged but that is not what we need.
While it is possible to use the ColumnAdded - it will probably execute only once foreach of the autogenerated column, the actual implementation could become an overkill and will be even less direct than already mentioned approaches.
If you will have some time and desire you could create your own DataGridView derived class, take Boolean isDataGridFormatted from your form and implement all the initialization(or event hooking) inside the custom DataGridView.

Using custom forms for editing DataRows

I have a DataSet which I want to visualize and work with. I use DataGridView components to display its tables, but when it comes to adding new rows/editing existing rows, I don't want to use DataGridView's functionality: I want to show a custom form instead, with TextBoxes, and ComboBoxes, and whatnot, and OK/Cancel buttons.
There is a table with Name (string), Forme (string), Image (byte[]), Attr1 (string), Attr2 (string), IsSpecial (bool) columns. Forme and Attr2 are nullable, the others are not, and Image should contain a picture in it. Also, Attr1 and Attr2 must be looked up from another table (which has ID (long), Name (string) columns).
So I create a new form, drop two textboxes, one picturebox, two combobxes, and a checkbox on it. I already have a problem: how to represent DBNull in a textbox/combobox?
Next, the binding itself. I reckon I have to do something like this:
class MainForm
{
// ...
private void btAdd_Click(object sender, EventArgs e)
{
using (EditFrom editForm = new EditForm())
{
// I have to create a new row, right?
var newRow = theTable.newStrongTypedRow();
if (editForm.ShowData(binding) == DialogResult.OK)
theTable.addStrongTypedRow(newRow);
}
}
private void btEdit_Click(object sender, EventArgs e)
{
using (EditFrom editForm = new EditForm())
{
if (editForm.ShowData(binding) == DialogResult.OK)
binding.EndEdit();
else
binding.CancelEdit();
}
}
}
class EditForm
{
// ...
public DialogResult ShowData(SomeBinding binding)
{
// tie the controls to the datarow which is being edited right now
BindAllControls(binding);
// let the user input the data
return ShowDialog();
}
}
But what do I use for "SomeBinding"? And what sould be inside BindAllControls()? Or maybe I have this all upside down and it's not how I am supposed to represent/edit data? Maybe someone could suggest a book about this topic?
I would think you would want to use a BindingSource to handle all your bindings.
You can configure the controls to bind to the BindingSource and it should handle all of the translation between the controls and the DataSet.
Bindings can be set like this:
this.nameTextBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.testDataBindingSource, "Name", true));
You could pass in your BindingSource as "SomeBinding".

Categories