Passing Datagridview to dataset - c#

Hello internet so first i am newbie at c# and i am doing project about changing data from a sql table. I passed the result of the query to the datatable and datagridview, but what i want next is i want the modified datagridview table passing to a dataset. this is how i get my table from the sql:
string query = "select Article,Barcode,\"Minimum Stock\",\"Current Stock\" from article where Fid=2 and \"Minimum Stock\" > \"Current Stock\"";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
da.Dispose();
Now the users will modifie the table and valid the information. How can i save it to a dataset?
I tried to bind dataset to the datagridview:
Dataset1.Tables.Add(datagridview1.datasource);
But it threw a error where it says datasource doesn't use here
Can anyone help?

Related

How to add a column when using SqlDataAdapter to fill a datagridview

I am using SQL to fill my datagridview. I am doing that this way:
string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cn);
string sql = "some text here";
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
Now it deletes the old datagridview and paste the selection. But I want just to add the data to the column right of the existing data.
Thanks in advance
This requirement sounds like it could be met with a SQL Inner Join in the query you're using in your SqlDataAdapter. If you were able to join your two data sources together on matching keys, you could simply pull the data down once. But I'm going to assume there's some reason why that won't work for you.
You can in fact do what you want with a DataSet, but you'll need to take a few more steps:
string sql = "The first query"
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, myConnection);
DataSet ds = new DataSet();
myConnection.Open();
dataadapter.Fill(ds, "Authors_table");
myConnection.Close();
// I don't know what your primary key is, but you need to have one.
// I am assuming it's called "author_id".
DataColumn authorIdColumn = ds.Tables["Authors_table"].Columns["author_id"];
ds.Tables["Authors_table"].PrimaryKey = new[] { authorIdColumn };
// Get your second set of data
sql = "My second query, which also has the same primary key, but has more columns"
dataadapter = new SqlDataAdapter(sql, myConnection);
dataadapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataSet ds2 = ds.Clone();
myConnection.Open();
dataadapter.Fill(ds2, "Authors_table");
myConnection.Close();
// Now we use the DataSet.Merge method, which is very powerful.
ds.Merge(ds2, false, MissingSchemaAction.AddWithKey);
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
You may have to experiment with that a lot: this is just the outline. Without knowing your data and what you do up to this point, it's hard to know what settings or methods you might also need to call.
Try this. I ran multiple queries in one go
SqlDataAdapter adapter = new SqlDataAdapter(
"SELECT * FROM Customers; SELECT * FROM Orders", connection);
adapter.TableMappings.Add("Table", "Customer");
adapter.TableMappings.Add("Table1", "Order");
adapter.Fill(ds);

Is it possible to fill a checkedlistbox with items from an sql database?

Sorry if this is a stupid question! I'm very new to coding and only have limited access to the internet whilst at work, I was just wondering if this is possible? and If so do you have a useful link for me to read over?
A quick overview of what I'm trying to do.
I have form1 and form2, form1 has a datagridview box that pulls data from the database, when I click on a cell it opens form2, which has a checklistbox which I want to now put code in so it pulls the data from a specific column and checks a box if the cell that was clicked applies to it.
Go easy on me if this question is stupid ^^, thanks in advance!
Some code I have produced so far! Which pulls the boxes from the database, but I also need to check the boxes too..
SqlConnection con = new SqlConnection("=");
con.Open();
string query = "select ID from dbo.report";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow datarow in dt.Rows)
{
checkedListBox1.Items.Add(datarow["ReportID"]);
Edited: put current coding in.
You can use below code to bind checkboxlist from database.
SqlConnection con = new SqlConnection("=");
con.Open();
string query = "select ID,NAME from dbo.report";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
checkedListBox1.DataValueField = "ID"
checkedListBox1.DataTextField = "NAME"
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DataBind();

Read data from a database in C#

I have created a table name glossary in a database named ChatBotDataBase in SQL Server. I want to read the data in a special column of the table.
To do so, I have written this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = #"Data Source=shirin;Initial Catalog=ChatBotDataBase;
Integrated Security=True";
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = sc;
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
But there is an error in last line.
The error is :
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll.
And here is a print screen of the mentioned table:
Can anyone help please?
Looks like you are confusing the Datatable called table with your database table in your sql server. In your image you show us the glossary table in your sql server, not the DataTable called table.
You get this error because you create an empty DataTable called table with DataTable table = new DataTable() but you didn't even fill your table. That's why it doesn't have any rows by default.
SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter.
using(SqlConnection sc = new SqlConnection(conString))
using(SqlCommand cmd = sc.CreateCommand())
{
cmd.CommandText = "SELECT * FROM glossary";
...
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
sda.Fill(table);
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
}
Below code will help you
sda.SelectCommand.CommandText = "SELECT * FROM glossary";
DataTable table = new DataTable();
sda.Fill(table , "glossary");
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
You haven't executed the query or populated the table. It is empty. It has no columns and no rows. Hence the error.
Frankly, though, I strongly suggest using a typed class model, not any kind of DataTable. With tools like "dapper", this can be as simple as:
var list = conn.Query<Glossary>("SELECT * FROM glossary").ToList();
With
public class Glossary {
public int Id {get;set}
public string String1 {get;set} // horrible name!
....
public int NumberOfUse {get;set}
}
Dear kindly first fill your table with the data.
And you should use checks because if there is no data then you get a proper message.check is below..
if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
else if(dt.Rows.Count > 0)
MessageBox.Show("Table is empty");
And other advice is that you should display data into DataGrid.... Displaying data from Database into a message box is not a good programming approach..
For displaying DataTable into DataGrid in C# is as simple as below.
SqlCommand cmd = new SqlCommand("select * from student",con);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
dt.TableName = "students";
da.Fill(dt);
dataGridView1.DataSource =dt;
using System.Data.Odbc;
OdbcConnection con = new OdbcConnection("<connectionstring>");
OdbcCommand com = new OdbcCommand("select * from TableX",con);
OdbcDataAdapter da = new OdbcDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds,"New");
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables["New"];
you can get the connection string from:
http://www.connectionstrings.com/

Use SQL Query at DataGridView in C#

How can i use this SQL query in C#? I want use it in a DataGridView.
SELECT dbo.tbl_moein.[ID-Kol],dbo.tbl_moein.ID,dbo.tbl_kol.Name,dbo.tbl_moein.name,dbo.tbl_moein.tell,dbo.tbl_moein.address,dbo.tbl_moein.remain FROM dbo.tbl_kol,dbo.tbl_moein
Hello you can try my code:
SqlConnection sqlconnection= new SqlConnection(""); // your sqlconn
DataTable dt = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT dbo.tbl_moein.[ID-Kol],dbo.tbl_moein.ID,dbo.tbl_kol.Name,dbo.tbl_moein.name,dbo.tbl_moein.tell,dbo.tbl_moein.address,dbo.tbl_moein.remain FROM dbo.tbl_kol,dbo.tbl_moein", sqlconnection);
SDA.Fill(dt);
dataGridView1.DataSource = dt;

Fill DataTable from SQL Server database

This one is a mystery for me, I know the code I took it from others, in my case the datatable it returns is empty
conSTR is the connection string, set as a global string
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
sqlConn.Close();
return dt;
}
EDIT 1
The whole point is to later show this table in a datagrid view on a tabcontrol, here is the question on that
displaying multiple datatable in tabcontrol C#
Here it just show's me a blank datagridview
EDIT 2
Tried them all, when I try to display the table, the datagridview is empty, have the right amount of rows but now value
If the variable table contains invalid characters (like a space) you should add square brackets around the variable.
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo.[" + table + "]";
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input
Try with following:
public DataTable fillDataTable(string table)
{
string query = "SELECT * FROM dstut.dbo." +table;
SqlConnection sqlConn = new SqlConnection(conSTR);
sqlConn.Open();
SqlCommand cmd = new SqlCommand(query, sqlConn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
sqlConn.Close();
return dt;
}
Hope it is helpful.

Categories

Resources