Customize gridview c# windows application - c#

My Table has 10 columns fetched from a database, while I need to bind only 4 columns of it to a DataGridView in that 4 column 3 columns from database one of them should add dynamically(This column not in database) extra Windows application c#
string sql1 = "Select * From Table";
SqlConnection connection1 = new SqlConnection(constring);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql1, connection1);
DataSet ds1 = new DataSet();
connection1.Open();
dataadapter.Fill(ds1, Reporttype_tbl1);
connection1.Close();
dataGridView2.DataSource = ds1;
dataGridView2.DataMember = Reporttype_tbl1;

If you need extra processing beyond the data that you have in your table you could:
(Imagine that you want to calculate the revenue, giving the income and expenses of a business)
Use the query itself to do the extra processing for these columns that are not in the database.
For example: SELECT Name, Income, Expenses, Revenue = Income - Expenses FROM TABLE
In this case, the Revenue will be calculated as the query runs.
Use your C# code to do the extra processing and change your datasource to the new one.
For example:
Add a Revenue column to your DataTable
Make the formula for each line
Use the new DataTable as DataSource
In this case, you are adding the data after the query has been completed, using your C# code to the calculations.
Picking the right one depends on whats kind of work you are wanting to do and what you feel more comfortable.

Related

C# 1 datagridview 2 databases where statement

Is it possible to add data from 2 tables in 1 datagridview.
And let table 2 add information that is equal with row[0].
The problem is Name is in another table as the needed information but ID's are matching.
Table 1 got : ID,Time and some other stuff.
Table 2 got : ID,Name.
So he needs to get the ID from row 0 and with Table 2 He needs to get the name WHERE ID is equal to Row 0
Yes it is possible to place two tables into the same datagridview. Run a query like this..
Select ID, name
From Table2
Where ID IN (
Select Top 1
ID
Table1
)
And then use this to fill a datatable, and set that as the data source of the datagridview.
Dont try to mess with DataGridView, Here is simple Solution based on ADO.NET
string select = "SELECT * FROM table1,table2 WHERE table1.ID=table2.ID";
MySqlConnection c = new MySqlConnection();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(select, c.con); //c.con is the connection string
MySqlCommandBuilder commandBuilder = new MySqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView.DataSource = ds.tables[0];

Appending DataRow to DataTable filled from DataAdapter, clears all records

I have a DataGridView that has a DataTable bound to it, populated from PostgreSQL database with Npgsql .NET data provider library.
Populating records works, but when I want to append just a single records to already existing DataTable, previous records vanish:
NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
DataTable tmpTable = new DataTable("tmpTable");
npDataAdapterSingle.Fill(tmpTable);
DSWeight.WeightRow row = this.dSWeight.Weight.NewWeightRow();
row.ItemArray = tmpTable.Rows[0].ItemArray;
this.dSWeight.Weight.Rows.InsertAt(row, 0); //Prepend, but i also tried this.dsWeight.Weight.Rows.Add(row);
If I select all records, without LIMIT'ing, then it works as expected. But I thought - why would i need to query the database all over again if I already have those records? That's why I want to LIMIT.
Maybe there is another solution, because I manually add new records to database and query them to add them to datatable, not the way it is supposed to be: add new records to datatable and them to database. I do it this way because I want the database to manage the id and timestamp fields and have datagridview to have these fields populated.
What am I missing?
Am not sure about the data type of DSWeight.WeightRow and the scope of 'this' object since I get to see only a portion of the code and not the full method. This should probably work for you. please have a try.
NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
DataTable tmpTable = new DataTable("tmpTable");
npDataAdapterSingle.Fill(tmpTable);
row = tmpTable.NewRow();
foreach (DataColumn col in tmpTable.Columns)
row[col.ColumnName] = tmpTable.Rows[0][col.ColumnName];
tmpTable.Rows.Add(row, 0);

Single datagridview row updating

Could you help with such problem:
I have two forms, datagridview and SQL database.
On Load event of my first form I'm select some data from my SQL database by using stored procedure(select query).
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("PROC001", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;
After that, I can filter or sort my datagridview by using dt.DefaultView.Filter = .... and display in my grid only filtered rows.
On CellMouseDoubleClick event my second Form2 appearing. In this form I update some value in database by clicking on Button1 and also after that I want to update my selected datagridview row. My quetions are:
1) How can I update only selected row in datagridview and do not execute stored procedure for all datagridview filling again.
2) My datagridview is already filtered, so if I execute procedure again, my filter has been disapeared. How can I avoid of this?
3) On Form2 I'm updating some database value, that is not included in my "select query" as selected field, but this value is affected on this query. Example:
SELECT Name, SecondName FROM tUsers
WHERE id = (SELECT DISTINCT id FROM tProcedures WHERE Code = 'First')
In my datagridview I can see Name and SecondName, but in Form2 I'm updating Code in tProcedures database table. So after updating I want to see my new data in datagridview, only in selected row and with current filter. I don't want to SELECT all data again to datagridview and broke my filter.
Is it possible to update single row? Could you provide some examples?
Because the DataGridView is using DataBinding, you have to update the underlying data source, in this case the DataTable. See How to: Edit Rows in a DataTable for how to do that.
For the filter issue, you would want to save and restore the filter:
var filter = dt.DefaultView.RowFilter;
UpdateData();
dt.DefaultView.RowFilter = filter;

immediate fetching of data from sql database from winforms textbox

I am using Winforms for my application & SQL Server as database.
I want that as soon as any text is typed in a textbox , immediate results are fetched/searched from the SQL SERVER database tables for that supplied text.
For this , i have given the following query:
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection();
public Form1()
{
conn.ConnectionString = "Trusted_Connection=true";
conn.Open();
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataTable dt = null;
SqlCommand cmd = new SqlCommand ("SELECT * FROM items WHERE item_name LIKE'" + textBox1.Text + "%'", conn);
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
dataGridView1.DataSource = dt;
}
}
But , as this fetches data every time from the database, so it takes more time, but i want a faster way. so shall i use DATASETS for this purpose, as datasets are used for disconnected environment.
OR
I shall first fetch the whole ITEM table from the database on to a GridView , & display it when the Form is opened.
now, when text is entered in the textbox , then it would not fetch data from the sql database, but would search in the GridView, so would this be faster?
which way would be efficient?
The item table has 3.4 million records.
How big is your items table?
If it's not big, it'll do to just store it in a dataset. Use the same textbox but search in the dataset.
If it's big, I would suggest using a timer. On each textchange, restart the timer of maybe 0.5 seconds. when the timer has elapsed, then only query the database. This prevents multiple queries while the user is typing.
Alternatively, if you could read the whole table and assign it to the AutoCompleteCustomSource:
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
foreach(DataRow row in dt.Rows)
textBox1.AutoCompleteCustomSource.Add(row["item_name"] as string);
Yes. Using a dataset and searching on it would be much faster. Since you are using WinForms, memory footprint is probably also not an issue unless you you are fetching a huge number of rows from the database.
Also, you should probably not search on every text change, but wait for a small amount of time say 2 seconds during which there are no changes to the textbox and then fetch. Otherwise you would be fetching for any new character entered in the textbox (i think).
Better approach will be using DataSet / DataTable. Read all the data from the Table on the form load and store it in the Form.

Inserting just a new record using DataSet (.net c# ado.net )

I've a form containing more than 200 text boxes in .NET desktop application. I want to insert them into their respective 4 tables of Database. Now how should I go about it using Dataset & DataAdapter to do this?
I mean usually this will be the flow:
Populate the DataSet using DataAdapter.Fill(Dataset,"DataTable");
manipuate the data of DataSet
DataAdapter.Update(Dataset,"DataTable") updates the content back to Database.
Code:http://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-intro.html#connector-net-tutorials-data-adapter
But here I just want to insert a new record in 3 different tables.
I think the way is to
Programmatically Create A dataset with 3 Datatables.
Bind 200 Textboxes to respective columns of these Datatabes
dataAdapter.Update(dataSet, dataTable.TableName);
Am I right?
How does dataAdapter.Update(dataSet, dataTable.TableName); work? Because, my each dataTable will have only one record. (the new record that is to be inserted. binded with those 200 TextBoxes of the form) where as the Table of the Database will have thousands of records. If I do dataAdapter.Update(dataSet, dataTable.TableName); will it delete all the rest of the records and insert this one alone?
I just want to insert a new record (without fetching other 1000s of records into my Dataset) into Database.Table using Dataset.
Each row has a RowState Property, this will be used by the dataAdapter. So if your dataset has only one new row, the row state will be DataRowState.Added. The DataAdapter will insert the row and change the row state to DataRowState.Unchanged. All other rows in the database will be unchanged.
IDbTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
foreach (DataTable dataTable in dataSet.Tables)
{
string sql = "SELECT * FROM " + dataTable.TableName + " WHERE 0 = 1";
SqlDataAdapter dataAdapter = new SqlDataAdapter (sql, dbConnection);
dataAdapter.Update(dataSet, dataTable.TableName);
}
}
catch
{
dbTransaction.Rollback();
throw;
}
dbTransaction.Commit();
Remark: Will not work if there are constraints in the database defined.
Simply make the SQL insert commands and execute them:
string cmd="insert into myTable(column1, column2, etc) values (#text1,#text2, etc)";
SqlCommand sqlcmd=new SqlCommand(cmd,mySqlConnection);
sqlcmd.Parameters.Add("#text1",SqlDbType.NChar,textbox1.Text);
sqlcmd.Parameters.Add("#text2",SqlDbType.NChar,textbox2.Text);
sqlcmd.ExecuteNonQuery();

Categories