How to Enter a Column of Data in Winforms Using C# - c#

I have a Winform App where I want a user to be able to enter some stock corrections against a list of products which will in turn create a database record for each of those corrections.
Using a combobox, I got it so each item would have to be selected in turn. It works great, but is not very user friendly. Ideally, I'd like a list of products with an empty column to enter the corrections, click submit and ya done.
I looked at using a datagrdiview. I can generate the list of products, but I've no idea on how to create the 'entry column'.
Any suggestions on the path to take?
Cheers,
Numb
EDIT
Here is a mock up of what I would like to do to make it as clear as possible without showing code...

If you want use a ”Submit” button to save a new stock correction, then
approach will be:
-Create a datagridview with products names and empty cell for stock correction
-After ”Submit” button was clicked read ”Correction” columns values, if value exists update database…
Here how you can do it:
Create a datagridview in designer dgvProductCorrections,
then create with designer a two columns in this datagridview
dgvProductCorrection_Product and dgvProductCorrection_Correction.
Put this(or your) columns names in Column .Name property
Then, I assume that you have a class Product where exists a property .Name,
you will need to put a name of this property(in my example will be Name) in .DataProperty of column
Above can be done with designer or in code(Constructor)
Adding a list products List<Product> lstProducts; in datagridview will be as:
dgvProductCorrections.DataSource = lstProducts; //(this may be in Form_Load)
Rememeber before adding a list set a datagridview property AutoGenerateColumns to False
dgvProductCorrections.AutoGenerateColumns = false;
in Button_Click event handler of your Submit button put a code where you loopin through a all rows and reading a correction values. After you can update a database with those values
//Code in Button_Click
{
foreach(DataGridVewRow dgvr in dgvProductCorrections.Rows)
{
Decimal fCorrection;
//Check if value exists and it can be used. Add own other checks
if(dgvr.Cells(this. dgvProductCorrection_Correction.Name).Value != null && Decimal.TryParse(dgvr.Cells(this.dgvProductCorrection_Correction.Name).Value.ToString(), fCorrection) = True)
{
//Here you can put a update code, or save a correction in list and then update all by one update call
}
}
}

Related

C# Winforms DataGridView: manipulating data by user input AND programmatically leads to first chance error

I have an input enabled DataGridView bound to a BindingSource which has a SortableBindingList as DataSource.
There is no direct connection to the database. The list is read once from the database beforehand. After the user is done with editing he can choose either to save the changed data to the database or not.
The list has 2 fields:
"Type" (enum)
"Path" (string)
As I want to use a ComboBox for the user to select the "Type" I add an additional column "TypeCbx" which is bound to the enum values. Initially, all "Type" values from the list are copied to the column "TypeCbx" and for changes, the value of "TypeCbx" is copied back to "Type" in the event ...CellEndEdit().
Furthermore, I have 2 button columns included:
"Browse" button: opens a FolderDialog for the user in order to adjust the actual row and set the column "Path" and (if it is a new row/entry) a default value to "Type"
"Remove" button: removes the row/entry from the DGV
This worked as long as I used an unbound DataTable in which I had the following code for the button "Browse":
private void dgvPaths_OpenFolderClick(DataGridView sender, DataGridViewCellEventArgs e) {
string newSelectedPath = Helper.FileBrowserDialog("Select folder", LastSelectedPath);
if (newSelectedPath != null) {
LastSelectedPath = Helper.CleanPath(newSelectedPath);
if (dgvPaths.Rows[e.RowIndex].IsNewRow) {
// --- variante old: unbound datatable ----------------------------------------
DataGridViewRow row = (DataGridViewRow)dgvPaths.Rows[0].Clone();
row.Cells[dgvPaths.Columns["Path"].Index].Value = LastSelectedPath;
row.Cells[dgvPaths.Columns["Type"].Index].Value = LibraryPathType.Movies;
row.Cells[dgvPaths.Columns["TypeCbx"].Index].Value = LibraryPathType.Movies;
row.Cells[dgvPaths.Columns["TypeCbx"].Index].ReadOnly = false;
dgvPaths.Rows.Add(row);
dgvPaths_CellValueChanged(sender, e);
} else if (dgvPaths.Rows[e.RowIndex].Cells["Path"].Value == null || LastSelectedPath != dgvPaths.Rows[e.RowIndex].Cells["Path"].Value.ToString()) {
dgvPaths.Rows[e.RowIndex].Cells["Path"].Value = LastSelectedPath;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].ReadOnly = false;
dgvPaths_CellValueChanged(sender, e);
}
}
}
Now, with the bound DataSource, the line dgvPaths.Rows.Add(row); no longer works. So I adjusted the code as follows:
// --- variante new 1: bound list, working on dgv -----------------------------
dgvPaths.Rows[e.RowIndex].Cells["Path"].Value = LastSelectedPath;
dgvPaths.Rows[e.RowIndex].Cells["Type"].Value = LibraryPathType.Movies;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].Value = LibraryPathType.Movies;
dgvPaths.Rows[e.RowIndex].Cells["TypeCbx"].ReadOnly = false;
dgvPaths_CellValueChanged(sender, e);
Issue 1:
Now, the data is written into the row of the DataGridView but the DataGridView does not interpret it as an input and therefore it is not really added - it still is a "new Row" waiting for input. I need to manually go into the Path Column of the row and press a key in order that the DataGridView accepts it as a valid entry and shows a new "new Row" line.
=> How can I inform the DataGridView that programmatically entered data should be handled like a user input?
Issue 2:
Furthermore, when I manually enter an entry in the DataGridView and click in the "Path" column between the added line and the new "new Row" line, a first chance exception is thrown.
=> What is the reason for the first chance exception?
Then I've read that you should not manipulate the DataGridView but instead the BindingSouce or BindingSource.DataSource, which I tried with by changing the code to this:
// --- variante new 2: bound list, working on datasource ----------------------
Library.Current.AddDirtyPath(LibraryPathType.Movies, LastSelectedPath);
Issue 3:
Hereby, I also get a first chance exception when this entry is added to the source list.
=> What is the reason for the first chance exception?
What is the correct approach here?
=> Do I need to manipulate the rows of the DataGridView or the entries of the BindingSource or the entries of the BindingSource.DataSource?
Issue 4:
The bound DataGridView threw another exception when loading the DataSource and there is no enum value for "0" (I guess for the "new Row" line). Therefore, I needed to add a dummy enum value which is set to "0" to my enum value list which I need to skip again for the actual ComboBox selection values. It works but it messes up the code.
=> Is it possible to avoid this dummy value, at all?
--- U P D A T E ---
After reading Caius recommendation, I have decided to update this question as I was able to follow the SBL approach and reduce the issues.
The correct approach here is to use a main "storage" SBL for all working data (which is initially filled by reading the DB) and create a filtered SBL out of it which is used as DS for the DGV where the user can work on and use sort and filter methods. By adding/updating/removing data, you have to ensure that all adjustments stay synchronous in the "storage" SBL. Then, when you want to update the DB, you use the 'storage' SBL.
Thereby only 1 issue is left: if you want to add a new line with a button column function inside the DGV itself. It fails as the state of the actual new line is changed while you are calling the add function from inside the DGV. There are 2 ways to "fix" this:
a) You need to completely(!) Clear() the SBL that is used as DS for the DGV and add the new line afterwards (according with all other existing ones from the "storage" list) back to this SBL. Thereby the state of the new line is also changed but as it is completely removed the state is also cleared. After this you need to Refresh() the DGV. Hereby, you will lose focus of the actual cell.
b) You use a hidden button outside of the DGV by btnAdd.PerformClick() which calls the add function in which you do not need to Clear() the SBL that is bound to the DGV. This seems strange but it works (whyever) and you keep the focus on the "new line" row (not on the added one).
All other functions like updating and removing an existing DGV line can be called by additional button columns within the DGV itself without issues.
The enum issue is not an issue as it is common to use a dummy zero value for empty entries. If I find out, how to get rid of the dummy value, I will update this question accordingly.
In order to fill the combobox column without a split between display and value columns you only need to ensure that the DataPropertyName of the combobox column is set like the DB column name.
--- U P D A T E: 2 ---
I have created a detailed video (tutorial) about my approach:
https://www.youtube.com/watch?v=W_afaNf7nz8
From 1:31:20 I show the difference between adding a new line by an external and an internal button and also the strange behaviour of using the method directly (=> error) or triggering an external button which uses the same method (=> no error).
What is the correct approach here?
You have a datagridview
You bind its DataSource to a datatable
You have a datagridviewcombobox
You bind it's DataSource to a completely different datatable
You tell the combo which columns, from its own datatable, are to be used for display, value and which column in the table that the grid is bound to, shall be updated/used for deciding which value to Show
var gdt = new DataTable();
gdt.Columns.Add("FileType", typeof(FileType));//enum
gdt.Columns.Add("Path");
gdt.Rows.Add(FileType.Text, "c:\my.txt");
var fdt = new DataTable();
fdt.Columns.Add("Val", typeof(FileType));//enum
fdt.Columns.Add("Disp");
foreach(FileType t in Enum.GetValues<FileType>())
{
fdt.Rows.Add(t, t.ToString());
}
//now wire it up
datagridviewWhatever.DataSource = gdt; //makes columns
var c = new DataGridViewComboBoxColumn();
c.DisplayMember = "Disp"; //name of column in fdt to use for show
c.ValueMember = "Val"; //name of column in fdt to use for value during lookup/set operations
c.DataPropertyName = "FileType"; //name of column in gdt that this combo shall show/set
c.DataSource = fdt; //set DataSource last (performance reasons)
Combo will now, for each row, get the value in gdt.FileType (eg FileType.Text), lookup the value in its own table fdt.Val, use the related value in fdt.Disp (eg "Text") to show in the list. If the user chooses a new list item (eg "Excel") it goes the other way, get the relevant Val (eg FileType.Excel) chosen and push it into gdt.FileType
I've never actually done it with enum typed values; can't see why it wouldn't work but if it gives trouble it might be simpler to switch to using ints instead of FileTypes - make all your typeof() calls typeof(int) and cast the FileType t to int in the foreach when adding it to the row collection.
Finally, when you're down with this as a concept I recommend throwing it all away and doing it using the visual designer - it will make a much better, nicer, easier to use job of it:
add a DataSet type file to your project
open it
if there is a database somewhere backing all this, right click on the design surface and choose Add TableAdapter, enter the connection string, choose a query, that returns rows, put SELECT * FROM MovieFiles WHERE ID = #id or whatever, call it FillById/GetDataById, finish
if there isn't a database backing all this just right click the surface, add a datatable called MovieFiles, right click it and add columns like FileType (set type to int in property grid), Path etc
right click a blank space and add another datatable called FileTypes, put a string column called Disp and an int column called Val (sounding familiar?)
save and switch to Forms designer. Open Data Sources tool panel (View menu.. other windows submenu)
Drag the MovieFiles node out of data sources and into the form. A datagridview appears as well as a bunch of stuff in the bottom tray. The grid is already correctly binded to the DataSet that contains the MovieFiles table. You can see all the code VS is writing for you in the Forms.Designer. It looks a lot like the code I put manually above
Edit the columns of the datagridview, change the file type column to be a combobox type, set the DataSource to the FileTypes table, DisplayMember to Disp, ValueMemberto Val. Check the DataPropertyName is still FileType in movies - this should also be familiar as it's the visual version of the code above)
the only thing left to do is put some code in the constructor that fills the FileTypes table from the enum (or to be honest, just make a table in the DB called FileTypes, have an int and a string column, add a tableadapter, select them.. that way you don't have to recompile the whole program when you add a file type)
Why do I advocate using these visually designed datatables rather than code ones? Because they're so much nicer in every single way. They have logical methods and named properties for columns, they just work with LINQ and they behave like .net classes that are collections of POCOs not 2D arrays of object that are indexed by string and need casting to make them useful. DataTable are awful to work with in comparison. They wrap around basic DataTable and do expose them but follow a rule that if you've exposed it, you've probably gone wrong
//no; using .Tables puts you back in "world of pain"
var p = (string)datasetX.Tables["MovieTypes"].Rows.Cast<DataRow>().First()["Path"];
//yes - using named property for MovieTypes is good, LINQ works, Path is a string property etc
var p = datasetX.MovieFiles.First().Path;

Saving unbound column in datagridview to a datatable

Hello I have not much experience in programming and haven't found any useful information regarding my question, that's why I need your help.
My goal is to create a datagridview that is databound by a local database (datatable), which is fully customazible by user. At first, when the user logins to main form if there was no previuos instance of editing, the datagridview will display nothing, however user can add columns by button (which specifies headertext, datatype and so on) and when added the datagridview will display the first column and then the user can edit the rows simply by clicking on the datagridview square (like MS excel). After that, the user can save the data by clicking on a save button, now the datatable will show the saved data, and the next time user will login, it will show the saved contents.
The situaton of now: I have 3 columns with data in the datatable, it is databounded to the datagridview and on debug it will show how it should be, I create the unbound column but it of course will not save after pressing the save button, thats because I have a problem with this code:
private void button3_Click(object sender, EventArgs e) // save button
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
cmd = new SqlCommand(#"INSERT INTO Inventorius VALUES ('" +
dataGridView1.Rows[i].Cells[j].Value + "')");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
I'm trying to find a specific algorithm that can insert all rows and columns to the datatable that are created/deleted in the datagridview.
I think I should also look into my function that adds the column, or is it irrelavent? Ah please do tell me if the goal is suitable in doing with datagridview, or is there any more better alternatives, thank you.
I think you're going about this the wrong way
I understand you want to provide the user the ability to create columns, but there are only a certain number of columns and what columns they are is dictated by the database design. You can't let the user arbitrarily add their own column (well.. you can but this seems to be not your goal)
Because there are a set of known columns you might as well just support them all, bind them all, have them all in your datagridview and then just make them all invisible (theColumn.Visible = false) and when the user chooses to "add" them, just make them Visible=true. They "look" like theyve been added but in reality they were always there, wired up and working properly, just hidden
I also think you're going about your data grid/table/access the wrong way (or, the hard way)
Add a new dataset to your project
Open it, right click the surface, add a tableadapter
Go through the wizard, selecting a connection string, saving it, adding a select that returns rows, select * from sometable where id = #id, call the methods FillBId/GetDataById, finish
Save the dataset
Switch to your form, open the Data Sources window (View menu, Other Windows), drag the node representing your datatable, onto the form - a datagridview appears along with some other componentry that will retrieve and save data, manage current rows etc
Put some code into the constructor after InitializeComponent():
foreach(DataGridViewColumn c in yourDataGridViewName.Columns)
c.Visible = false;
Wire up some way for the user to choose columns, perhaps a listbox with checkboxes that gets its items list from the datagridview columns collection
Pay attention to how the back end code is structured - when you dropped the grid on the form it writes some code too; that's how to load (fill) and save (tableadapter.update) the db too
Do not iterate over a datagridview pulling values out of it; it's a UI control for showing and editing the datatable to which it is bound. If you want to get access to values, get it via the datatable. If you want to save edited alues, it's just a single line of code: someTableAdapter.Update(someDataTableNameHere)

Binding user data on button press

I don't know a good way to explain this but what I have so far is I created a dataset and called it Database and created a table in it. Then I used a bindingsource and defined Database as its datasource.
Then I put the bindingsource as my datagrids data source and I put my textboxs text to the respective column in the bindingsource (e.g. textbox1 text=bindingsource - Name) so I can update my xml so I can click on the row and it fills the textboxes with the rows info and as i edit the text box it changes the data in the rows on the grid view so far an edit and update.
But I want to be able to have the option to update or not. So instead of I type and it changes I want to be able to fill in the boxes then choose to press update or cancel like a normal edit form.
This is my form
It's as if I could do something like
string = textboxname
then when I press update it then does selected row column "name" = string
ok so i figured it out thanks to devTimmy. i was looking in the wrong place and with the wrong ideas.
iv now done it so it takes the selected row index and uses that to fill in the correct row when its told which cell to fill. i didn't think to tell it which cell before so it failed and i thought no more of it.
here is my code.
int i;
i = dataGridView1.CurrentRow.Index;
dataGridView1.Rows[i].Cells[0].Value = Nametb.Text;
dataGridView1.Rows[i].Cells[1].Value = Locationtb.Text;
dataGridView1.Rows[i].Cells[2].Value = Infotb.Text;
dataGridView1.Rows[i].Cells[3].Value = dayvisittb.Text;
database1.WriteXml("Database.xml");

Open a form based on a row selection from a datagrid

Out of curiosity is it possible to open a form based on row selection in a datagrid? I would also need the form to show information based on the username in the datagrid. The persons username is included within the row of the datagrid.
You will have to code this, but yes, it is possible.
First, populate your DataGrid with data that you can handle.
On the DataGrid's Selection Changed event, read that data, create the form you want to show (if it does not already exist), and display it using Show().
This would be like a typical Menu program.
You can handle this under the following event
dataGridView1_CellClick
Get the CurrentCell value of the datagridiview
Check for the username exists or not as per you asked and show the respective form
Sample code:
if (this.dataGridView1.CurrentCell != null)
{
string strusrname=dataGridView1.CurrentCell.Value.ToString();
//Here find out for the user name from the string as you get the currentcell value of the datagridview
// Raise the corresponding form as per you required
}
Not really sure if this is what your after, as i don't no if you want to show the data on another pre-built form or create a new one, but here it goes.
This way you won't even need to worry about the row selected, assuming you have the username of the person bound to the datagrid you can create a hyperlinkcolumn like this:
<asp:HyperLinkcolumn DataNavigateUrlField="Username"
DataNavigateUrlFormatString="PersonForm.aspx?Username={0}"
HeaderText="More Details"
Text="View Person Details" />
Then the PersonForm can load the persons details. Or if you would like some help on how to catch the selected row on itemcommand then let me no.
Hope this helps.
EDIT: after your winforms tag update you may be interested in this: DataGridViewLink On MSDN
The general code is:
DataGridViewLinkColumn links = new DataGridViewLinkColumn();
links.UseColumnTextForLinkValue = true;
links.HeaderText = ColumnName.ReportsTo.ToString();
links.DataPropertyName = //Set your field here.
links.ActiveLinkColor = Color.White;
links.LinkBehavior = LinkBehavior.SystemDefault;
links.LinkColor = Color.Blue;
links.TrackVisitedState = true;
links.VisitedLinkColor = Color.YellowGreen;
DataGridView1.Columns.Add(links);
Once you have added a link you can catch it using DataGridView1_CellContentClick and do what you want with it, ie open a new form or alter the current one.

Easiest way to synchronize a dialog form with a datagridview row?

I have a datagridview with a row id from a database. I want to open a dialog form pointing to to the same row. What's the syntax for doing something like
Detail.BindingContext = Gridform.BindingContext
Since my other question was close
https://stackoverflow.com/questions/1527887/how-to-point-to-use-same-datasource-and-currencymanager-from-a-second-c-form
I update this one: I prefer a solution with the currency manager.
I'm not sure what you're trying to do. I believe you want to be able to select a row in a DataGridView, do something to open a dialog with another DGV that has the same record and select that record in the dialog.
If this is what you want to do then you need to do two things: get the id of a selected row in the main form's DGV, and then programmatically select a row in another DGV. Here's how you might do this:
Step 1. Get the id of the selected row on the main form.
Something roughly like this should work:
string id = dataGridView.SelectedRows[0].Cells[colIdColumn.Index].Value.ToString();
where:
a. The column that has the id you mention is named colIdColumn
b. The data type of id is string
After you've validated id, open your dialog and pass it id. When the dialog opens conitnue to step 2.
Step 2. Programmatically select a row on another DataGridView
Look at the BindingSource.Find method to return the index that a value appears in a BindingSource and look at the BindingSource.Position property to select a record in a BindingSource.
Your code might look something like this:
// Get index of row with your id.
int index = yourBindingSource.Find("YourIdProperty", "Id");
yourBindingSource.Position = index;
Hope that helps

Categories