I've a database in MS Access.
And i'm placing the data in the database to datagridview on form load.
string connectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "/Db.mdb";
OleDbConnection conObj = new OleDbConnection(connectionString);
conObj.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter da = new OleDbDataAdapter();
da = new OleDbDataAdapter("SELECT * FROM StopMaster", conObj);
da.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
conObj.Close();
on execution, it'll show datagridview with the items in the database,
along with an empty row where we can add new data
and if we click on the existing row's items with data we can update it and even remove it
how to code for that update delete and add and reflect to the database
is there any event or what
also how can i make data grid view columns not resizable.
also say if i have two columns "name" and "pin code" in the datagridview when i click on column header say for now "pin code"it must sort the datagridview rows in order
is there any event and how to for that too
The first thing to mention, is that you will need to Bind your data table to the Datagridview. This is so that any changes you make whilst editing the DataGridView control reflect directly through to the underlying DataTable.
I'll assume that you have already populated the DataTable object.
You start by creating BindingSource object :-
BindingSource bs = new BindingSource();
bs.Datasource = dt;
Now we need to make this Binding Object the datasource for your DataGridView Control :-
dataGridView1.DataSource = bs;
In a method, you can use the following code to commit changes :-
using (OleDbConnection con = new OleDbConnection(connectionString))
{
var adaptor = new OleDbDataAdapter();
adaptor.SelectCommand = new OleDbCommand(""SELECT * FROM [StopMaster]", con);
var cbr = new OleDbCommandBuilder(adaptor);
cbr.GetDeleteCommand();
cbr.GetInsertCommand();
cbr.GetUpdateCommand();
try
{
con.Open();
adaptor.Update(dt);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message, "OledbException Error");
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Exception Error");
}
}
Related
I've a datagridview and two buttons which get data from sql server DB. Whenever i click on btn1 it fetches the datagridview with the record AND if i then click btn2 it combines the btn2 records with the btn1 records.
How can i clear the datagridview so that btn2 will show me it records and not combinig the records?
clear:
DataSet.Clear();
http://msdn.microsoft.com/en-us/library/system.data.dataset.clear.aspx
Add below is a example of Populating a datagridview with sql query results.
string select = "SELECT * FROM EXAMPLETABLE";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView.DataSource = ds.tables[0];
In my database I have 4 column. I fetch this database value in a datagridview. But I want to add two columns in datagridview. So, I want to make a datagridview with 6 columns. Within this 6 columns 4 columns will filled by database value. How can I do this?
OleDbConnection con = new OleDbConnection("CONNECTION STRING");
con.Open();
DataTable dtusers = new DataTable();
OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
dataGridView1.Columns[0].Name = "Code ";
dataGridView1.Columns[1].Name = "Description";
dataGridView1.Columns[2].Name = "Qnty";
dataGridView1.Columns[3].Name = "Rate";
con.Close();
Here are 4 columns. Code,Description,Qnty,Rate. I want to add two more columns in this datagridview. Amount and Narration. But Amount and Narration columns are not present in PurchaseTable.How can I do this?
If you want blank columns then create them and insert. If the data is in the database then add a join to your query to retrieve the data.
Adding blank columns
DataGridView dgv = new DataGridView();
dgv.DataSource = dtusers;
DataGridViewColumn amount = new DataGridViewColumn();
amount.HeaderText = "Amount";
amount.Name = "Amount";
dgv.Columns.Insert(0, amount);
DataGridViewColumn narration = new DataGridViewColumn();
narration.HeaderText = "Narration";
narration.Name = "Narration";
dgv.Columns.Insert(0, narration);
Assumed that you already have dtusers ..
Do Column adding to dtuser .. http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx
Do looping for all rows in your table to fill your new column
Assign the table as dgv datasource .. dataGridView1.DataSource = dtusers;
Because your column names are hardcoded, I think you can create a predefined columns in your datagridview through designer(Click datagridview -> choose Edit Columns).
Create all 6 columns you want. On the first four set DataPropertyName to name of the column from your query. Last two leave empty.
And remember set datagridview.AutoGeneratedColumns = false; before you binding data to datagridview...(somewhere in form_Load handler)
After this your code will be:
using (OleDbConnection con = new OleDbConnection("CONNECTION STRING"))
{
con.Open();
DataTable dtusers = new DataTable();
using(OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
}
con.Close();
}
I'm pretty certain this is a problem with my data binding, but I'm not for sure what the problem is exactly. Using mysql I'm getting rows showing up in my dataset, but no rows showing up in my datagridview after I do the binding.
conn = new MySqlConnection("server=localhost;database=mydb;uid=user;password=pass");
conn.Open();
grid = new DataGridView();
grid.Dock = DockStyle.Fill;
ds = new DataSet();
adpt = new MySqlDataAdapter("select * from test limit 6;", conn);
adpt.Fill(ds);
Debug.WriteLine("data set rows found " + ds.Tables[0].Rows.Count);
binding = new BindingSource();
binding.DataSource = ds;
grid.DataSource = binding;
Debug.WriteLine("data grid rows found " + grid.Rows.Count);
conn.Close();
Controls.Add(grid);
The debug printout for this is 6 and 0. Does anybody know where my problem is?
Thanks in advance!
just do
grid.DataSource = ds.Tables[0];
Or.. If you want to using the BindingSource (say for filtering), set
binding.DataSource = ds.Tables[0];
Rather than use the designer I'm trying to populate a DataGridView I've put on my Winform programmatically. When I look in the table under the debugger it has the correct columns and number of rows. The problem is the grid appears as an empty grey box on my form. When I bind the grid to the database via VS 2008 Designer it worked fine. How can I track down the problem?
UPDATE
I pretty much took this from this MSDN Article
UPDATE
Do I have to do anything in the designer other than drop the grid on the Winform?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Windows.Forms;
namespace CC
{
public partial class Form1 : Form
{
private BindingSource bindingSource1 = new BindingSource();
private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
public Form1()
{
InitializeComponent();
dataGridView1 = new DataGridView();
this.Load += new System.EventHandler(Form1_Load);
this.Text = "Cars";
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Cars");
}
private void GetData(string selectCommand)
{
string dbPath = "c:\\temp\\cars.db";
try
{
var connectionString = "Data Source=" + dbPath + ";Version=3";
dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
}
I think you need to specify the DataMember property. And I think you don't require binding source object, directly you can bind DataTable to DataGridView control.
I am attaching a code which helps to bind gridview control with SQL Server database, and it works fine for me.
using(SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter("SELECT * FROM Table1",
"Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
this.dataGridView1.DataSource = dataTable;
}
}
Sorry I don't have SQLite installed :(
basically i dont think u should complicate this! here's an easy way:
string cs = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your db location;"; //connection string
string sql = "SELECT * FROM table_name"; //sql statment to display all data
OleDbConnection conn = new OleDbConnection(cs); //connectiion
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //data adapter object
DataSet ds = new DataSet(); //dataset object to keep data in table
conn.Open(); //open connection
da.Fill(ds, "table_name"); // fill the dataset with table_name through data adapter
conn.Close(); //close connection
dataGridView1.DataSource = ds; //populate the datagridview with dataset
dataGridView1.DataMember = "table_name"; // populate datagridview with table_name
I have has difficulties with sqlite and also binding with linq. Now I have the same issue as above and ended up looping the data table to fill the grid.
I have noticed other minor issues with sqlite when using datatables and also databinding so I guess the problem lies with sqlite.
Here's some code to save time for anyone.
int rowcount = 0;
foreach (DataRow row in dataTable.Rows)
{
dataGrid.Rows.Add();
int column = 0;
foreach (var item in row.ItemArray)
{
dataGrid.Rows[rowcount].Cells[column].Value = item;
column++;
}
rowcount++;
}
I am doing some c# and mysql and I was successful at getting mysql data into a grid view for the first time! Now, my main question is, how do I manage the grid view style with this? For example, say I have already created columns and such, how do I put the mysql data into a specific column in the grid view?
Below is the code that is actually loading the data into the grid view.
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("SELECT * FROM `swipes`", conn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
Also, this creates columns based on the mysql data, how do I modify the width of these columns and such, or like stated above, use my own custom columns for my data? I've never done any mysql work in any UI, so I'm open to suggestions and tutorials as well. Thanks in advance!
If you really want to do this (as someone has already stated you should look at other options) you can create the columns in the designer and set the DataGridViewColumn.DataPropertyName on each column to the columns returned by the autogenerated dataset. Remember to turn of autogeneration of columns (AutoGenerateColumns) on the grid. This way you have full control of the column styles.
try this
string connection = "server=localhost;database=adil;user=root;password=";
MySqlConnection con = new MySqlConnection(connection);
con.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = con;
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from studentrec";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;