In my windows form I have to create a table (at runtime) of specified by the user name (in textbox) and then use this table as datasource of DataGridView. Finally, the filled table must be inserted into the database. I tried to solve this problem in two ways:
I have created a DataTable, specified its columns etc. but I couldn't insert the DataTable into the database, even using SqlDataAdapter.Update() - propably I misused DataAdapter. I'm working with C# for 1 week and I don't fully understand the idea of DataSets, TableAdapters etc. So I decided to use SQL commands.
Using ExecuteNonQuery() I've created table in my database, then I recognized, that I have to use magic SqlDataAdapter and I gave up.
I want to manage the content of DataGridView in the same way, as in the case of DataTable added to DataSet using configuration wizard.
I know, that I can skip DataGridView, create list of textboxes, button expanding this list, and function inserting all fields into my table after confirmation button, but my supervisor expects DataGridView.
I can't paste the code here, because I left only copy of source code on company computer. If it will be necessary I will paste here my code tomorrow.
try to use the method either RowValidating or CellValidating of DataGridView
private void dataGridViewEnterTab1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (dataGridViewEnterTab1.IsCurrentRowDirty) // Trigger when the row is dirty or has changed
{
string userName = dataGridViewEnterTab1["UserNameCol", e.RowIndex].EditedFormattedValue.ToString();
//...Your SqlDataAdapter or codes
}
}
I hope it will help this idea. :)
Related
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)
I've set up a simple data bound gridview that is populated via the autogenerated code for winforms. It is filling based off of the dataset I point it at.
I've updated the underlying database it's supposed to be filling off of to add an additional column to a table. However this added column is not appearing in the gridview.
I have deleted the datset and rebound it and can't find an answer online but am probably searching with incorrect terms. Is there a way to refresh the dataset in some way?
How the gridview is being filled is by:
this.xTableAdapter.Fill(this.DBDataSet.tableName);
I imagine there is a simple way to refresh the underlying dataset but cannot for the life of me find what it is.
This link had the answer. I needed to go into the dataset designer view and right click on the get, fill() query in the query area for my table. Doing so allowed me to modify the query that built the dataset, adding in the missing column.
Ok so I'm trying to make a simple SQL CE Viewer application just to view my local databases for another application, I have it setup so that I can select what database I want to open and then it automatically populates a combo box with all of the tables in the database. When I select a table it populates a DataGridView with the records in the table.
My problem is switching between tables. I can't seem to get the DataGridView to remove everything from the previous table and re-populate the DataGridView with the new table information. Of course each table has different columns and rows and such.
I've googled and searched on here and every suggestion I find doesn't seem to work. It populates the DataGridView with the first table just fine, but when I select another it basically adds the columns and rows into whatever was there....
How can I get the DataGridView to completely clear for new data?
And please don't tell me to use dataGridView1.DataSource = null; tried that, doesn't work.
Well, I checked it in one of my programs and just changing DataSource property is working fine. I didn't have to use datagridview.Refresh(). Maybe it depends on the kind of DataSource, which you are using to set datagridview data?
Write this line after you have done populating the DataSource with the new data
dataGridView1.Refresh();
You don't need to clear the DataGridView directly. Its always handled by modifying the DataSource of the DataGridView.
If there is nothing else in the form, you can simply call InitializeComponent() again. But I think #Josh is right.
I have used a ultragrid in my windows application to show records of a table of my database by set its DataSource property to the datatable that returns from that table.
the number of rows can be about 100000 rows.
Now i have 2 questions:
1) I want to let user to select several rows of this grid and then edit them all.to do this i need to know which cells of these selected rows have same values and which of them have not and then show the same columns in a form.
the first solution i thought about, was check all columns of all selected rows through 2 foreach loop.Is there any better solution for this??
2)finally when the user press save button, the updates should apply on the table.what is the best way to do this??? (Use IN command or UpdateCommand of sqldataadapter or ...)
According to my analysis,
1) you can do the grouping in the ultragrid based on which all columns you want to see and save the data. After grouping the similar columns would appear together and it will save a lot of time in data analysis and figuring out which column data are same in different rows. Once you have got the list of similar data you vcan handle them easily through for each loop or even for loop as you would be able to access the count of rows thus generated.
2) You should look at using the System.Data.SqlClient.SqlBulkCopy for this. Here's the documentation, and of course there are plenty of tutorials online.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx
One should avoid IN when no. of records are more as it affects the performance. If you dont want to use sqlbulkcopy, then you can also go for UpdateData() of ultragrid(very useful feature of ultragrid)
You can use the UltraGrid provided method call UpdateData() to update all the multiple rows with out need to track changes row by row or by cell
The UpdateData method updates any modified information in the grid, sending it to the data provider. When the update is complete, any rows that were marked as having modified data will have that mark cleared.
The UpdateMethod needs to exit from cells that are still in edit mode, this is a bug and to resolve it you will need to use it as shown below
ultraGrid1.PerformAction(Infragistics.Win.UltraWinGrid.UltraGridAction.ExitEditMode);
ultraGrid1.UpdateData();
More details on why to use it this way can be found here http://devcenter.infragistics.com/Support/KnowledgeBaseArticle.Aspx?ArticleID=4220
To answer you 2nd question you will have to use the UpdateData method this way
e.g.
private void ultraButton1_Click(object sender, EventArgs e)
{
ultraGrid1.UpdateData();
this.dbRowsTableAdapter.Update(this.testDataSet);
ultraButton1.Enabled = false;
}
Again it seems UltraGrid keeps its local data pure to itself hence you will have to call the Update method of the TableAdapter, which means you will have to create a DataSet and fill it with the SqlDataAdapter.
Please see forum explaining clearly why UltraGrid.UpdateData method does not commit back to database here http://www.infragistics.com/community/forums/t/57161.aspx
I could not find any solution for my first question so i have used loop to compare all selected rows of my grid and diagnose the common values.
but i have used SqlBulkCopy for my second question.
I have used full join to populate my datagridview with the contents of two tables, now I want to save the contents of the datagridview into a single table.
I don't want to use loops and I don't wanna access single cells of the datagridview.
Now anyone has a solution for this ?
and using datasource of the datagridview and its adapter is not the solution,so please reply honestly after understanding my problem.
How about using your full join to populate the Third Table, then bind the third table to the DataGridView, therefor when you make changes to the DataGridView the third table is updated automatically
try this. I created a new winforms project, i added a button and a datgridview. I created a public datatable and gave it columns and a row in the Form1 constructor. When you click the button it displays the number of rows contained in the datatable. So I run the program click the button MessageBox says 1 I add a row to the datagrid view and click the button Messagebox says 2
//public/Global datatable
public DataTable myTable = new DataTable();
public Form1()
{
InitializeComponent();
//create myTable Columns
myTable.Columns.Add("Name");
myTable.Columns.Add("Age");
myTable.Columns.Add("Number");
//add one row
myTable.Rows.Add(new object[] {"myName","myAge","myNumber"});
bind to the datagridview
dataGridView1.DataSource = myTable;
}
private void button1_Click(object sender, EventArgs e)
{
//display the number or rows in the datatable
MessageBox.Show(myTable.Rows.Count.ToString());
}
}
I'm not sure I understand what you're asking for, but I will attempt to be of service. You are obtaining a result set that combines two tables using a full join, and then want to output that result set into a third table? Is that correct?
First, I would recommend creating a view for this third table. That is probably the most efficient and dynamic solution. If you want to present that data to your users, have the datagrid bind to the view. If you made any changes to the two original tables, you would have to update the third "by hand". A view does this automatically.