I have DataGrid that shows some values from MySQL database. I need that if I click on any column, the value will be saved to string. Is it even possible?
Here´s the code that shows mysql table in the datagrid
try
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select Jméno from info", conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "LoadDataBinding");
dataGridCustomers.DataContext = ds;
}
catch
{
WarnWindow vv1 = new WarnWindow(1);
vv1.ShowDialog();
}
finally
{
conn.Close();
}
But if I click on (for example) Bohumil Homola, this value shall be saved as:
string name = Bohumil Homola (column value);
Finally I got it. Here´s the code which I used:
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)datagridname
.ItemContainerGenerator
.ContainerFromIndex(datagridname.SelectedIndex);
DataGridCell RowColumn = datagridname.Columns[0].GetCellContent(row).Parent as DataGridCell;
string ContentOfCell = ((TextBlock)RowColumn.Content).Text;
I am using a grid to be bounded through code whose columns are defined at design time.
My code for binding the grid in the form_load() is :
private void SearchForm_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
try
{
cn = db.createConnection();
if (cn.State == System.Data.ConnectionState.Open)
cn.Close();
cn.Open();
cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy')as BillDt from BillMaster", cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}
ds.Dispose();
cmd.Dispose();
da.Dispose();
cn.Close();
}
I debugged the program and the data is assigned to the each field that is observed from the Immediate Window while debugging but when the form is displayed the data does not appear. And number of blank row as fetched from the dataset are created.
How do I solve this? Please help.
Try this:
dataGridView1.DataSource = ds; // dataset
dataGridView1.DataMember = "TableName";//TableName
Hope it will work.
I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}
How to insert the database access column in combobox, on button click?it has 1 column
Try this:
create a private method that get msaccess data and bind to a datatable:
private DataTable BindData()
{
using (var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\YOURDB.mdb; PersSecurity Info=False;")) /your connectionsting
{
using (var dAd = new OleDbDataAdapter("select ID,column1 from Table ", conn)) //select query from your DB
{
var dSet = new DataTable();
try
{
conn.Open();
dAd.Fill(dSet);
return dSet;
}
catch
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
}
Then on your button click Add
var dt = BindData();
cmbBox.DataSource = dt;
cmbBox.DisplayMember = "column1"; //Display Table Column on your DB
cmbBox.ValueMember = "ID";
See also:
The C# Station ADO.NET Tutorial
Regards
I am trying to populate a list box from a customers table in SQL database.I tested with WPF list box the code is working good but when i try to implement in asp.net web application i am unable to populate the list box. Here is my code
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query , conn);
da.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
listbox1.SelectedValue = row["customer_ID"].ToString();
samplelist.Add(listbox1.SelectedValue);
}
listbox1.DataSource = samplelist;
}
catch (Exception)
{
}
Can any one guide me in the right direction ?
Try using the below code:
try
{
string query = "SELECT customer_ID FROM Customers WHERE ID = 1";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(ds);
listbox1.DataSource = ds.Tables[0];
listbox1.DataTextField = "WORKSTATION_ID";
listbox1.DataValueField = "WORKSTATION_ID";
listbox1.DataBind();
}
catch (Exception)
{
}
foreach (DataRow row in ds.Tables[0].Rows)
{
samplelist.Add(row["WORKSTATION_ID"].ToString());
}
listbox1.DataSource = samplelist;
listbox1.DataBind();
You should be able to trim this down somewhat to the following. You're missing the DataBind() as well.:
try
{
//Existing to fill ds, check table exists, etc.
listbox1.DataSource = ds.Tables[0];
listbox1.DataValueField = "COLUMNNAME";
listbox1.DataTextField = "COLUMNNAME";
listbox1.DataBind();
}
catch (Exception)
{
}