I am creating a inventory app using c# that pulls its info from sql server. I am making it a tabbed view, with each tab representing a different type of item. I have included some of my code, what I am trying to figure is, is there a better way to do this? I dont feel like the way I am doing is right, even though it works. All my queries for each tab are stored procedures. Secondly, How would I insert and update the database through the grid?
public partial class InventoryWindow : Window
{
private InventoryDS InvDS;
private String connString = "server=PC-server;database=Inventory;user=user;password=password";
String sqlString_Routers = InventoryOutputQuery.InventorySummary_Routers();
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
}
private void showTaps()
{
String sqlString_Taps = InventoryOutputQuery.InventorySummary_Routers();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Routers, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showPower()
{
String sqlString_Power = InventoryOutputQuery.InventorySummary_Power();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Power, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
private void showSwitches()
{
String sqlString_Switches = InventoryOutputQuery.InventorySummary_Switches();
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand(sqlString_Switches, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
And below is how i bind it to the grid:
public void BindGrid(string view)
{
switch (view.ToUpper())
{
case "Routers":
showTaps();
break;
case "POWER":
showPower();
break;
case "SWITCHES":
showSwitches();
break;
case "HUBS":
showHubs();
private void tcDataView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TabItem ti = tcDataView.SelectedItem as TabItem;
if (ti != null)
BindGrid(ti.Header.ToString());
}
break;
My suggestion is to be careful with how we handle SqlConnection. It is a scarce resource and it will run out pretty soon if we are not careful.
Please wrap sql code in a using block, for example:
using (SqlConnection con = new SqlConnection(connString))
{
SqlDataAdapter adpt = new SqlDataAdapter(sqlString_Routers, con);
DataSet ds = new DataSet();
adpt.Fill(ds, sqlString_Routers);
dgDataView.DataContext = ds;
}
The following link will explain the effect of 'using' block in a bit more details.
http://www.codeproject.com/KB/cs/tinguusingstatement.aspx
Related
I want to use two DataGridViews in this form, which will receive their information from two different tables in one database. But when I run the program, both DataGridViews only display the second table information.
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
dataGridView1.Columns[3].Visible = false;
}
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView2.DataSource = dt;
dataGridView2.DataBind();
}
}
Try this
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
dt = new DataTable();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
You seem to be reusing da and dt. Reusing da is no problem, but reusing dt is. When you assign dt to DataGridView.DataSource, the data is NOT copied! So in the end, both DataGridViews will be using the same DataTable object, that holds the data from the second table (medal).
You could try this:
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
DataTable dt1 = new DataTable();
da.Fill(dt1);
dataGridView1.DataSource = dt1;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
DataTable dt2 = new DataTable();
da.Fill(dt2);
dataGridView2.DataSource = dt2;
}
Edit: renamed the local DataTable variables for clarity.
I have a GridView. I am trying to display DB table data into grid using DataTable. So I am saving the query result in DataTable, but the data is not displayed. Here is my code. Please help.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dataTable = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString;
string query = "select * from GridExcel";
SqlConnection con1 = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con1);
con1.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your
datatable
da.Fill(dataTable);
Gridview1.DataSource = dataTable;
Gridview1.DataBind();
ViewState["CurrentTable"] = dataTable;
con1.Close();
}
}
Try to use a DataReader:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dataTable = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["gridconnection"].ConnectionString;
string query = "select * from GridExcel";
SqlConnection con1 = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(query, con1);
con1.Open();
// create data adapter
SqlDataReader reader = cmd.ExecuteReader();
// this will query your database and return the result to your datatable
dataTable.Load(reader);
Gridview1.DataSource = dataTable;
Gridview1.DataBind();
ViewState["CurrentTable"] = dataTable;
con1.Close();
}
}
The below code is works for me.
string constring = #"Data Source=.\SQL2005;Initial Catalog=gridconnection;";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("select * from GridExcel", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
I am writing a c# windows forms application and i am coming accross the error mentioned above. I think this is happening because i am opening an sql connection and reader object in my main form load object and then doing the same thing again in another click event handler. I am not sure what i need to do in order to change my code / stop this from happening (or if this is even the problem). I have tried turning MARS on in my connection string but this did not fix the problem. Below is my code.
namespace Excel_Importer
{
public partial class Export : Form
{
public Export()
{
InitializeComponent();
}
private void cmbItemLookup_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Export_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings ["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Select * From ExportItem", conn);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ExportItemName", typeof(string));
dt.Load(rdr);
cmbItemLookup.DisplayMember = "ExportItemName";
cmbItemLookup.DataSource = dt;
conn.Close();
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn);
SqlDataReader rdr2;
rdr2 = cmd2.ExecuteReader();
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
You need to close your DataReaders. They implement the IDisposable interface, so the simplest thing is to put them inside a using block:
using (rdr = cmd.ExecuteReader())
{
..
} // .NET always calls Dispose() for you here
Actually, you pretty much have to dispose of everything that implements IDisposable, or problems gonna happen.
As the other answer points out, you must tidy up your clicked event code:
private void btnLoad_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString) )
{
conn.Open();
using(SqlCommand cmd2 = new SqlCommand("Select * from " + cmbItemLookup.Text, conn) )
{
using(SqlDataReader rdr2= cmd2.ExecuteReader())
{
try
{
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd2;
DataTable dt = new DataTable();
ada.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dgvExport.DataSource = bs;
ada.Update(dt);
conn.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
}
}
}
I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);
So here I'm trying to populate my dropdown list, the code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataReader ddlvalues = mycommand.ExecuteReader();
ddlTransactionCategory.DataSource = ddlvalues;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
the problem is, I can't seem to get it to work, any help? and is this code doing it right?
plz try below code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataAdapter adp =new SqlDataAdapter(mycommand);
DataSet ds =new DataSet();
adp.Fill(ds);
ddlTransactionCategory.DataSource = ds;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
Thanks,
Hitesh
Can't bind to a SqlDataReader (or at least I've never tried it). Get a DataTable or a DataSet instead, fill it and then bind that to the dropdown the same way.
Use SqlDataAdataper like the one below
using (SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from MSUnit", con);
DataTable dt = new DataTable
da.Fill(dt)
ddlTransactionCategory.DataSource = dt;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
}
if you want to use DataReader you must insert one-by-one.
while (ddlvalues.Read())
{
ddlTransactionCategory.Items.Add(new ListItem(ddlvalues.getString("OrgID"),ddlvalues.getString("categoryCode")))
}