I'm trying to take information from my SQL server and load it into a datagridview based on paramaters selected by the user. The example I post at the end of this question worked in an earlier function in the program, but now it isn't. This leads me to believe that the issue lies in the line that actually outputs the data to the DGV. Any thoughts on why it's not filling up the DGV? I've included two examples, neither of which is working. For some reason, they're just not inputting any information into the DGV, even though I know from debugging that they are indeed pulling the information from the server successfully.
SqlConnection DBConnection = new SqlConnection(ConnectionString);
//Opens the connection
DBConnection.Open();
//Creates a string to hold the query
string query = "SELECT * FROM PRD WHERE PRD_NUM LIKE '" +OutputBeforeIncrement + "%'";
//Creates an SQLCommand object to hold the data returned by the query
SqlCommand queryCommand = new SqlCommand(query, DBConnection);
//Uses the aforementioned SQLCommand to create an SQLDataReader object
SqlDataReader queryCommandReader = queryCommand.ExecuteReader();
//Creates a DataTable to hold the data
DataTable dataTable = new DataTable();
//This part actually loads the data from the query into the table
dataTable.Load(queryCommandReader);
dgvOutput.DataSource = dataTable;
The other example:
using (SqlDataAdapter newDA = new SqlDataAdapter(query, DBConnection))
{
DataTable Table = new DataTable();
newDA.Fill(Table);
dgvOutput.DataSource = Table;
}
You might try this or something similar:
SqlDataAdapter myDataAdapter;
SqlCommandBuilder myCommandBuilder;
SqlCommand mySqlCommand = new SqlCommand(myQuery, MySQLConnection);
//I think this is the default command type, and thus can be omitted
mySqlCommand.CommandType = CommandType.Text;
myDataAdapter = new SqlDataAdapter(mySqlCommand);
//Automates your insert/update/delete
myCommandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.Fill(myDataTable);
dgvOutput.DataSource = myDataTable.DefaultView;
Related
I am trying to edit a cell in a RadGridView which has a datasource set from data from an SQL view.
What I was hoping to do was to populate the grid from the view, allow edits then manually update the associated tables when a user click an "Update" button.
As soon as the user enters data into a cell and leaves the cell is presents with an error "Specified method is not supported".
I assume it's trying to update the datasource with the new value so I am trying to work out how to tell it not to.
I am populating the table with:
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = " + drpSRID.Text, con);
SqlDataReader reader = cmd.ExecuteReader();
radGridView1.DataSource = reader;
}
According to RadGrid data binding documentation, the DataSource property accepts instances of the following types:
DataSet
DataTable
DataView
Array of DataRow
Any object collection that implements these interfaces:
IListSource
IList
IEnumerable
ICustomTypeDescriptor
Based from reference inspection, SqlDataReader doesn't supported because it doesn't implement those interfaces mentioned above, hence NotSupportedException has thrown when binding SqlDataReader contents into DataSource property directly.
As a workaround, you may create new DataTable instance and fill its contents from SqlDataReader like this:
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = " + drpSRID.Text, con);
SqlDataReader reader = cmd.ExecuteReader();
// fill DataTable contents
dt.Load(reader);
// assign DataTable as data source instead
radGridView1.DataSource = dt;
}
// DataBind goes here
Note:
The string concatenation to build SQL query may prone to SQL injection. Using parameters when passing server control value to SQL query is more recommended way:
var dt = new DataTable();
using (SqlConnection con = new SqlConnection(mydatasource))
{
con.Open();
SqlCommand cmd = new SqlCommand("select SRID, Name, Result from EditBatchResultsView where SRID = #SRID", con);
cmd.Parameters.Add("#SRID", SqlDbType.VarChar).Value = drpSRID.Text;
SqlDataReader reader = cmd.ExecuteReader();
// fill DataTable contents
dt.Load(reader);
// assign DataTable as data source instead
radGridView1.DataSource = dt;
}
Related issue:
Populate data table from data reader
In C# I want to use access data to fill my textBox I Am using ADO.Net To connect to access.So far I've got this:
OleDbConnection con = new OleDbConnection(Price.constr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection=con;
cmd.CommandText = "select * from Table1";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Price.constr is my connection String.
I want to fill textBox1 with the data in the Price Column Where my row ID = 1.(For Example)
If you want to read only one record from your table then there is no need to return the whole table and use an adapter to fill a datatable. You can simply ask the database to return just the record you are interested in.
string cmdText = "select * from Table1 WHERE ID = 1";
using(OleDbConnection con = new OleDbConnection(Price.constr))
using(OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
textBox1.Text = reader["Price"].ToString();
else
textBox1.Text = "No record found";
}
}
I have enclose the connection, command and reader in an using statement because these are disposable objects and it is a good practice to destroy them when you have finished to use them. (In particular the connection could cause problems if you don't dispose it)
Notice also that I have used the constant 1 to retrieve the record. I bet that you want this to be dynamic and in this case I suggest you to look at how to PARAMETRIZE your queries. (Don't do string concatenations)
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/
I'm trying to design a method to allow me to take a row from a SQL database using a SELECT. I then want to INSERT the returned row into an identical table on a database which resides on a different server.
My server connection and SELECT statement both work; I can view the row I want copied in a console window.
The issue I'm having is figuring out what data structure I need to use in C#, how to populate this data structure with the SELECT, and finally how to use that data structure to INSERT the row.
I'd like to keep the option for multiple rows open, but for now if I could get a single row transferring across it would be fantastic.
Thank you.
Edit: I've been able to work through this myself after a bunch of research. I've included my code below in the heop it helps someone else, but although it works, it is far from ideal. I am an amateur and it is not yet complete.
static public void CopyDatabaseRows(string ConnectionStringDEV, string ConnectionStringLOCAL, string queryString)
{
//Connect to first database table to retreive row/rows and populate dataset + datatable.
DataSet dataSet = new DataSet();
SqlConnection conn = new SqlConnection(ConnectionStringDEV);
conn.Open();
SqlCommand command = new SqlCommand(queryString, conn);
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, conn);
dataAdapter.FillSchema(dataSet, SchemaType.Mapped);
dataAdapter.Fill(dataSet, "dbo.FileRegister");
dataTable = dataSet.Tables["dbo.FileRegister"];
conn.Close();
//Connect to second Database and Insert row/rows.
SqlConnection conn2 = new SqlConnection(ConnectionStringLOCAL);
conn2.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn2);
bulkCopy.DestinationTableName = "dbo.FileRegister";
bulkCopy.WriteToServer(dataTable);
}
I'd suggest you use something like Simple.Data (https://github.com/markrendle/Simple.Data) to do this really easily. Because it uses C# dynamics, you can just load the dynamic type, and insert it directly into a second Simple.Data connection without worrying about type conversion.
Something like:
var db = Database.OpenConnection("data source=.;initial catalog=Xyz;etc");
var db2 = Database.OpenConnection("data source=somewhereElse;initial catalog=Xyz;etc");
dynamic user = db.Users.FindById(1);
db2.Users.Insert(user);
It works perfectly... I modified this code... Use it...
string local = "Server=destinationservername;Database=destinationserverdb;Uid=sa;Pwd=<Password>;
string dev = "Server=sourceservername;Database=sourceserverdb;Uid=sa;Pwd=Password;
private void btncopy_Click(object sender, EventArgs e)
{
CopyDatabaseRows(dev, local, query);
}
static public void CopyDatabaseRows(string ConnectionStringDEV, string ConnectionStringLOCAL, string queryString)
{
//Connect to first database table to retreive row/rows and populate dataset + datatable.
DataSet dataSet = new DataSet();
SqlConnection conn = new SqlConnection(ConnectionStringDEV);
conn.Open();
SqlCommand command = new SqlCommand(queryString, conn);
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, conn);
dataAdapter.FillSchema(dataSet, SchemaType.Mapped);
dataAdapter.Fill(dataSet, "dbo.DeviceLogs");
dataTable = dataSet.Tables["dbo.DeviceLogs"];
conn.Close();
//Connect to second Database and Insert row/rows.
SqlConnection conn2 = new SqlConnection(ConnectionStringLOCAL);
conn2.Open();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn2);
bulkCopy.DestinationTableName = "dbo.DeviceLogs";
bulkCopy.WriteToServer(dataTable);
MessageBox.Show(dataTable.Rows.Count.ToString() + " rows copied successfully", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Using VS2005 with C#
I want to fill the combobox by using the table value.
Code
OdbcConnection con = new OdbcConnection();
OdbcCommand cmd;
con.ConnectionString = "";
con.Open();
cmd = new OdbcCommand("Select no from table", con);
ada = new OdbcDataAdapter(cmd);
ds = new DataSet();
ada.Fill(ds);
combobox1.Items.Add(ds);
But no values was loading in the combobox, what wrong with my above mentioned code.
can any provide a solution for the probelm....
You do have something in your real connection string, right?
You're loading your data into a DataSet - that's a collection of tables and relations. How should the combobox know what table's data to display?? If the DataSet has multiple tables in it, you would have to additionally define which one of those to use. If the DataSet has only one table inside, then it's a waste of resources to use a DataSet in the first place.
If you only have a single set of data, use a DataTable instead:
con.Open();
cmd = new OdbcCommand("Select no from table", con);
ada = new OdbcDataAdapter(cmd);
DataTable data = new DataTable();
ada.Fill(data);
// define the column to be used to display text in the combobox
combobox1.DataTextField = "FirstName";
// define the column to be used as the value for the selection in the combobox
combobox1.DataValueField = "CustomerID";
combobox1.DataSource = data;
combobox1.DataBind();