I have a dataGridView that loads its data from an SQL server with the Data Source utility:
However when I trigger the following code:
using (var conn = new SqlConnection(connectionString))
{
string sql = "SELECT * FROM AssetManagement_copy";
using (var cmd = new SqlCommand(sql, conn))
{
sda = new SqlDataAdapter(cmd);
sda.Fill(filteredTable);
dataGridView1.DataSource = filteredTable;
}
}
The Serial No. column of the dataGridView loses its data?
Any ideas as to why this might be happening? I don't do any specific column manipulation or specify any dataColumn in the code to do anything with.
Thanks all!
Related
I have a table with a Column XML type named XMLContent.
When I load this table into DataGridView I see all columns without XMLContent (the column is empty in the DataGridView). How can I do to fix this?
This is my C# code:
using (SqlConnection sqlconnection = new SqlConnection(GetConnectionString()))
{
sqlconnection.Open();
string query = "Select * from RAP_HISTO_FIC_MAT order by FicName ASC";
using (SqlCommand cmd = new SqlCommand(query, sqlconnection))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
SqlParameter xmlColum = new SqlParameter();
DataTable records = new DataTable();
sda.Fill(records);
dataGridView1.DataSource = records;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
}
sqlconnection.Close();
}
Good day sir and ma'am. I'm planning to get all row header like "column_id and first_name, last_name and so on" and populate my listbox with row header from mysql database table. Please enlighten me how to do this. I am not sure what to use MySqlDataAdapter or MySqlDataReader. I'm beginner and willing to learn.
using (MySqlConnection conns2 = new MySqlConnection(connString))
{
conns2.Open();
MySqlCommand comm2 = new MySqlCommand("SELECT * FROM table1",
conns2);
MySqlDataAdapter add2 = new MySqlDataAdapter(comm2);
DataTable dt2 = new DataTable();
add2.Fill(dt2);
foreach(DataColumn column in dt2.Columns)
{
columnlistbox.Items.Add(dt2.Columns);
//it shows "collection" and exactly the number of row header
//but it doesn't show like "First name, client_id and last
//name"
}
conns2.Close();
}
for get columns names from a DataTable
If you need data from the db, and you load it into a DataTable (using DbDataAdapter or DbDataReader), you can know the column names from the DataTable.Columns collection property:
foreach (DataColumn col in dt2.Columns)
columnlistbox.Items.Add(col.ColumnName);
get only schema from MySql db (tables, columns ect)
but if you not need any data from the DB, but only its structure, you can use the DbDataReader. for load this data by the reader, a query must be "simulated" to the database:
using (MySqlConnection conns2 = new MySqlConnection(connString))
{
conns2.Open();
MySqlCommand comm2 = new MySqlCommand("SELECT * FROM table1", conns2);
using (var reader = MySqlCommand.ExecuteReader(CommandBehavior.SchemaOnly))
{
reader.Read();
var dtSchema = reader.GetSchemaTable();
foreach (DataRow row in tableSchema.Rows)
columnlistbox.Items.Add(row["ColumnName"]);
}
}
form https://stackoverflow.com/a/7159610/1271037:
Using the MySqlDataAdapter is the appropriate choice based on the sample code you provided because you are populating a DataTable and in ADO.NET DataAdapters are traditionally used to populate DataTables. A DataAdapter populates or "fills" your DataTable object.
You could also use a DataReader to populate your DataTable:
var dataReader = cmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
DataAdapters and DataReaders are a core design concept of ADO.NET, whether using Sql Server or MySQL database. A DataReader is a forward only, light and faster Database query helper. A DataAdapter is a bit heavier than a DataReader and also does more than a DataReader can do, it is possible that a DataAdapter uses a DataReader behind the scenes.
Here is how you would use the data from your MySQL database, you need to use a DataGrid, not a ListBox
using (MySqlConnection conn = new MySqlConnection(connString))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM table1",
conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
//display your dataset in a ASP.NET Web Forms DataGrid
dataGrid.DataSource = dt;
dataGrid.DataBind();
//conn.Close();// you do not need this, your using statements call Dispose and Dispose will release the connection back to the connection pool
}
You can get pointers from this code. In summary GetName is what you are looking for.
using (Common.DbCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "SELECT * FROM table1";
dynamic dr = cmd.ExecuteReader();
int index = 0;
List<string> columns = new List<string>();
for (index = 0; index <= dr.FieldCount - 1; index++) {
columns.Add(dr.GetName(index));
}
}
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 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.
I understand that with PHP I can use mysql_query($sql); and mysql_fetch_array($result); to fetch some MySQL data and place it into an array. How is this achieved in C# to where I could place my data in say, a datagrid?
This is probably the most quintessential ADO.NET code to fill DataGrid you're going to see (using disconnected DataSets, that is):
DataTable results = new DataTable();
using(MySqlConnection conn = new MySqlConnection(connString))
{
using(MySqlCommand command = new MySqlCommand(sqlQuery, conn))
{
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
conn.Open();
adapter.Fill(results);
}
}
someDataGrid.DataSource = results;
someDataGrid.DataBind();