I want to select all customer information where customerid = the selected customerid stored in the combo box and show the result in datagridview I tried this code but the gridview doesnot show result.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
int id = Convert.ToInt32(comboBox1.SelectedValue);
string cmdstring=string.Format("select *from customers where customer_id={0}",id);
SqlCommand cmd = new SqlCommand(cmdstring,con);
//cmd.Parameters.AddWithValue("#id",id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//da.Fill(ds, "customers");
//dataGridView1.DataSource = ds.Tables["customers"];
con.Open();
SqlDataReader red = cmd.ExecuteReader();
con.Close();
dataGridView1.DataSource = red;
button = new DataGridViewButtonColumn();
button.HeaderText = "edit";
button.Tag = ds.Tables["customers"].Columns["customer_id"];
dataGridView1.Columns.Add(button);
}
you could always make a DataBase Class and if you need to refactor this Class to pass in Connection String or read Connection string from .Config File you can use this as a template to get started plus it's a lot cleaner
Notice that I am returning a DataTable you can use this if you like just a suggestion
public class ClassDataManagement
{
public DataTable GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
if you want to use DataSet instead of DataTable replace where i have DataTable with
or change the method to return a DataSet like this below
public DataSet GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
after returning the ds you will need to bind it like this
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
I'm fairly certain that you're not getting any data because you're closing the connection before binding, and because you're using an incompatible type as your data source:
con.Close();
dataGridView1.DataSource = red;
Set the data source prior to closing the connection, or at least be sure to populate the data (for data readers, the data are populated as you enumerate). Additionally, DataGridView.DataSource indicates that it must use one of four interfaces: IList, IListSource, IBindingList, and IBindingListSource. SqlDataReader does not support these. I recommend reading DataAdapters and DataReaders, as this outlines some of the features that are for populating this kind of control.
Related
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/
how to pass ds from sql class to form class
in my form class
sqlCls floor = new sqlCls();
floor.getByFloor(floorNo);
reportFormDataGridView.DataSource = ds.Tables[0]; ******
in sql class . floor method
public DataSet getByFloor(int floorNo)
{
DataSet ds = new DataSet();
SqlConnection conn = connectionCls.openConnection();
SqlCommand com = new SqlCommand("select * from table where floorsNo = " + floorNo, conn);
SqlDataAdapter SE_ADAPTAR = new SqlDataAdapter(com);
SE_ADAPTAR.Fill(ds);
conn.Close();
return ds;
}
GridViews can take a DataSet as the DataSource just fine, no need to use a table.
Just do this:
sqlCls floor = new sqlCls();
var ds = floor.getByFloor(floorNo);
reportFormDataGridView.DataSource = ds;
You have a SQL Injection vulnerability in your code. Please consider using SQL parameters instead of unsanitized input.
So in your case it would be:
public DataSet getByFloor(int floorNo)
{
DataSet ds = new DataSet();
SqlConnection conn = connectionCls.openConnection();
SqlCommand com = new SqlCommand("select * from table where floorsNo = #floorsNo", conn);
com.Parameters.AddWithValue("#floorsNo", floorNo);
using(SqlDataAdapter SE_ADAPTAR = new SqlDataAdapter(com))
{
SE_ADAPTAR.Fill(ds);
conn.Close();
}
return ds;
}
SqlDataAdapter implements the IDisposable interface so you can wrap it in a using block to automatically dispose of resources when execution flow leaves the scope.
I am trying to save a dataset to a database. I got a dataset from another class, Now changes will be made on the form by a user on a datagridview, then the changed Dataset needs to be saved in the database.
I am using the below code; Its not generating any errors, but the data is not being saved in the database.
public class myForm
{
DataSet myDataSet = new DataSet();
public void PouplateGridView()
{
try
{
SqlService sql = new SqlService(connectionString); // Valid Connection String, No Errors
myDataSet = sql.ExecuteSqlDataSet("SELECT * FROM Qualification"); // Returns a DataSet
myDataGridView.DataSource = myDataSet.Tables[0];
myDataGridView.AutoGenerateColumns = true;
myDataGridView.AutoResizeColumns();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException + Environment.NewLine + ex.Message, "Error");
this.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//myDataSet.AcceptChanges();EDIT:Don't know why, but this line wasn't letting the chane in db happen.
SqlCommand sc = new SqlCommand("SELECT * FROM Qualification", sql.Connection); //ADDED after Replies
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(da); //ADDED after replies
da.Update(myDataSet.Tables[0]);
}
}
public class mySqlService
{
public DataSet ExecuteSqlDataSet(string sql)
{
SqlCommand cmd = new SqlCommand();
this.Connect();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandTimeout = this.CommandTimeout;
cmd.Connection = _connection;
if (_transaction != null) cmd.Transaction = _transaction;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds);
da.Dispose();
cmd.Dispose();
if (this.AutoCloseConnection) this.Disconnect();
return ds;
}
}
What am I doing wrong here? There are ways on the web to save the dataset, if the datset is created, edited and saved in the same class etc., BUT I would like to have the select dataset method in the mySqlService class. How should I, now can save the dataset to the database?
EDIT:
I have commented the three lines that were required to make the code work. The code works now.
In order to run Update method of SqlDataAdapter you must have to configure InsertCommand, DeleteCommand and UpdateCommand properties along with SelectCommand of SqlDataAdapter or construct the SqlCommandBuilder object which configure these commands implicitly.
Hey try following this tutorial here http://support.microsoft.com/kb/308507 first and then adapt it to your needs.
i have a grid view that is filled through a data-source from the code behind :
protected void Page_Load(object sender, EventArgs e)
{
// filling the grid view
MainGrid.DataSource = Update();
MainGrid.DataBind();
}
protected DataSet Update()
{
SqlConnection conn = new SqlConnection(#"ConnectionString");
SqlCommand cmd = new SqlCommand("SELECT tim,com,pic FROM ten", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
but i have a file upload that inserts the file-path into the database (and it works fine), but i would like to know how to change the column type to image through the code-behind.
thanks
The answer is - from the comments - set your column types in the declaration of the grid, and bind your data in the code behind.
If you need variable column types, the simplest route is to include multiple columns, and show and hide them appropriately.
You need to dispose all the disposable objects using the Dispose()....or like
using (SqlConnection conn = new SqlConnection(#"ConnectionString"))
{
using (SqlCommand cmd = new SqlCommand("SELECT tim,com,pic FROM ten", conn))
{
conn.Open();
using (DataSet ds = new DataSet())
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
MainGrid.DataSource = ds;
}
}
conn.Close();
}
}
I am pulling data from a sql server and putting it into a grid using c#. When the data displays on the grid, it is showing up as the guid rather than the actual name. How do I get the name to show and not the uniqe identifier. Any ideas? Thanks.
Here is some of the code:
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter("select * from Item", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "Item");
dgDataView.DataContext = ds;
//dgDataView.DataMember = "Item";
showdata();
}
}
private void showdata()
{
String connString = "server=server;database=database;user=user;password=password";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Item", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
You are using select * from Item and therefore returning all columns. You could just specify the columns you want in the Grid, in the order you want them. The grid by default has autocolumn generation on.
You can also specify the columns you want and what fields they map to using the columns DataMember values.
I figured this out, I just wrote my own query to display certain columns instead of automatically showing all of them.