I am having a strange problem and I have no clue whether it is happening due to bad connection or something else is causing this.
The problem I have a combo box and I am populating the values using SQL Data Table in "Form Load" event and it was working fine until today. Every time the form loaded both the combo boxes are empty one for date and other for company name. The code I am using is below.
public DataTable getResult(string query)
{
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandTimeout = 0;
da.SelectCommand = cmd;
da.Fill(dt);
return dt;
}
private void Reports_Load(object sender, EventArgs e)
{
RevenueDate_dt = func.getResult(dateQuery);
foreach (DataRow dr in RevenueDate_dt.Rows)
{
comboBox1.Items.Add(dr["Global_Period_Month"].ToString());
}
Gpn_dt = func.getResult(GpnQuery);
foreach (DataRow dr in Gpn_dt.Rows)
{
comboBox2.Items.Add(dr["gpnname"].ToString());
}
}
The query showing perfect result when I am executing it on SQL Server.
Looking forward for answers.
It's hard to say what's happening, but I wonder if the datatable isn't a little overkill for what you want. It seems a normal DataReader would have a lot less overhead and would be easier to debug. Something like this:
public string[] getResult(string query, string ColumnName)
{
List<string> results = new List<string>();
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandTimeout = 0;
SqlDataReader reader = cmd.ExecuteReader();
int col = reader.GetOrdinal(ColumnName);
while (reader.Read())
{
results.Add(reader.GetString(col));
}
reader.Close();
return results.ToArray();
}
And then to add the items to your combo boxes, it would simply look like this:
comboBox1.Items.AddRange(func.getResult(dateQuery, "Global_Period_Month"));
comboBox2.Items.AddRange(func.getResult(GpnQuery, "gpnname"));
Related
I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand
(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue
(
"#companyName",
textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.
I am trying to load mssql server database table (one column) value to a combo box... But I couldn't.. I have given the Connection String in App.Config file. So I'm finding difficulties in retrieving column values to the combo box.
The following is the code that I used.
private void StockInventoryManager_Load(object sender, EventArgs e)
{
cmbcategory.Items.Clear();
SqlCommand cmd = dcon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select Cat_name FROM Category";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cmbcategory.Items.Add(dr["Cat_name"].ToString());
}
}
I am trying to query my mySQL database and want all rows returning in an array which is accessible in a way like.
rows[0]["column"]
rows[1]["column"].
My code is currently:
MySqlCommand cmd = new MySqlCommand(query, conn);
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
var rows = dt.AsEnumerable().ToArray();
So I can use rows[0]["column"] but rows[1] is out of reach, as if the dt.Load hasn't scanned all rows and added them to the list.
I give you some pseudo code here, I did not try to compile it but should give you the idea, in general do not use static indexes like "1" to access the second row in the table, better have a loop or some other kind of dynamic approach which would always work no matter on how many records your query returns.
look at this, omitted exception handling for compactness
using(var conn = new MySqlConnection(connectionString))
using(var cmd = conn.CreateCommand())
{
conn.Open();
cmd.ComamndText = query;
var adp = new MySqlDataAdapter(cmd);
var dt = new DataTable();
adp.Fill(dt);
// here you can use the table's rows array to retrieve results
// for example
foreach (var row in dt.Rows)
{
//Do what you want now with this row
}
}
I am doing this for my own learning. It is not home work. All example I have found are for asp solutions.
I have a Grid and a DropDownList in a Winform.
The Grid has a DataSet a BindingSource and a TableAdapter.
I populate the dropdownlist with the tables in the DB as following:
public void FillDropDownList(string connString)
{
String Query = "SELECT * FROM information_schema.tables where Table_Name like 'Table%'";
using (var cn = new SqlConnection(connString))
{
cn.Open();
DataTable dt = new DataTable();
try
{
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (SqlException e)
{
//to be completed
}
radDropDownList1.DataSource = dt;
radDropDownList1.ValueMember = "TABLE_NAME";
radDropDownList1.DisplayMember = "TABLE_NAME";
}
}
The line that loads the data in the grid is like this:
this.table_xxxTableAdapter.Fill(this.xxxDataSet.Table_xxx);
So I suspect that with these components I would need a new dataset for each table but I do not like to do that because new tables may be created in the future.
How can I change the table loaded in the grid selecting tables from the dropdownlist?
A DataSet requires that you specify the tables you may want to load at design time, but it sounds like you want to load these tables dynamically (because they may get added to the database from another source?)
If I'm understanding your question correctly, you should simply do this:
Whenever the user selects a table, load the selected table using a dynamic query and re-databind the grid to it. The code should look something like this. Note: This is untested code.
protected void radDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string query = BuildQuery(radDropDownList.SelectedValue); //Pass in the table name
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
ad.Fill(dt);
}
}
catch (SqlException e)
{
//TODO: Handle this exception.
}
}
radGrid.DataSource = dt;
radGrid.DataBind();
}
private string BuildQuery(string table)
{
//TODO: Provide your own implementation for your query.
return string.Format(
#"SELECT * FROM {0}", table);
}
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.