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;
Related
I insert data from my database to combobox, and now I want to display value of this combobox into label, but every time instead of getting value of combobox, I get System.Data.DataRowView in my label.
I use this code for connection, it works fine:
OracleConnectionStringBuilder sb = new OracleConnectionStringBuilder();
sb.DataSource = "localhost";
sb.UserID = "library";
sb.Password = "library";
OracleConnection conn = new OracleConnection(sb.ToString());
conn.Open();
OracleDataAdapter TITLES = new OracleDataAdapter("SELECT NAME FROM TITLE", conn);
DataTable dt = new DataTable();
TITLES.Fill(dt);
cmbBooks.DisplayMember = "NAME";
cmbBooks.DataSource = dt;
conn.Close();
And then I want to get SelectedItem using this code:
label1.Text = cmbBooks.Items[cmbBooks.SelectedIndex].ToString();
How to solve it?
You can use the GetItemText method:
label1.Text = cmbBooks.GetItemText(cmbBooks.SelectedItem);
I want to delete a row from my data set,update the content of the listbox and update the content of the database.I have the following piece of code but it seems like nothing happens,all the rows are still there.
What am I not doing?
DataSet ds = new DataSet();
SqlDataAdapter daf = new SqlDataAdapter();
ds.Tables["Film"].Constraints.Add("PK_Film", ds.Tables["Film"].Columns["id"], true);
int ind = listBoxchildren.SelectedIndex;
listBoxchildren.DataSource = null;
ds.Tables["Film"].Rows[ind].Delete();
ds.Tables["Film"].AcceptChanges();
daf.Update(ds,"Film");
listBoxchildren.DataSource = ds;
listBoxchildren.DisplayMember = "Director.fk_FilmDir.title";
Unbound the data source before deleting the item,
int selectedIndex = listBoxchildren.SelectedIndex;
listBoxchildren.DataSource = null;
ds.Tables["Film"].Rows[selectedIndex].Delete();
ds.Tables["Film"].AcceptChanges();
daf.Update(ds,"Film");
listBoxchildren.DataSource = ds;
I have DLL class to call the table
public DataTable GetTemTableValue(string TableName)
{
SqlConnection conn = new SqlConnection(sConnectionString);
conn.Open();
string query = "select * from " + TableName + "";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
DataTable ds = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ds;
}
and i am binding the table to grid view
private void LoadData()
{
clsDataAccess objDAL = new clsDataAccess();
DataTable DS = new DataTable();
string objBLL = DDLTemTableList.SelectedValue.ToString();
DS = objDAL.GetTemTableValue(objBLL);
if (DS != null && DS.Rows.Count != 0)
{
lblNoRecord.Visible = false;
foreach (DataColumn col in DS.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GVDataEntry.Columns.Add(bfield);
}
GVDataEntry.DataSource = DS;
GVDataEntry.DataBind();
GVDataEntry.Visible = true;
}
else
{
lblNoRecord.Visible = true;
GVDataEntry.DataSource = null;
GVDataEntry.DataBind();
//GVDataEntry.EmptyDataText = "No recorddata found";
}
so Table is loading to Grid View. every time when i change the tables in dropdownbox and press search button columns will change dynamically so how can i update data in Grid view through using RowEditing,RowUpdating function and i need to store the date in database?
I have a DataGridView made of a DataSet of a table from the DB. When I delete a row, it is updated in the database but it is not removed from the GridView. Only when I restart the application does it get removed from the GridView.
Please help
You need to reset the binding on your bindingsource.
bindingSource.ResetBindings(false);
This is a very simple process.
1.) Create a Binding Source
2.) Set the Datasource for this object to your Dataset Table.
3.) Set The datasource for your DatagridView as the Binding source Object.
Code Example:
Dataset ds = new Dataset();
BindingSource bs = new BindingSource()
bs.Datasource = ds.Table[0];
DatagridView.Datasource = bs;
Now, Any changes you make in the DataTable will ripple through to your GridView automatically.
Hope this helps you?
if you are showing your table in dgv and for deleting something from that table you have a button on your win form. you chose let's say ID and click "delete" button for delting an item from db table. Here is that code:
private void btn_Delete_Click(object sender, EventArgs e)
{
int selectedCellCount = dgv.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
string selection;
for (int i = 0; i < selectedCellCount; i++)
{
selection = dgv.SelectedCells[i].Value.ToString();
string qs_delete = "DELETE FROM yor_table WHERE id = '" + selection + "';";
try
{
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = qs_delete;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
//don't forget to load your table again in dgv
string qs_select = "SELECT * FROM your_table";
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Clear();
dgv.DataSource = dataTable;
try
{
conn = new MySqlConnection(cs);
cmd = new MySqlCommand(qs_select, conn);
conn.Open();
da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
cb = new MySqlCommandBuilder(da);
dgv.DataSource = dataTable;
dgv.DataMember = dataTable.TableName;
dgv.AutoResizeColumns();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
You'll notice here that i have MySQL db but don't bother yourself with that.
If database is updated and you want to refresh DataGridView, call this:
this.<table name>TableAdapter.Fill(this.<DB name>DataSet.<table name>);
For example: Where is name of your table (for example Customers) and is name of your database (for example MyDB).
this.CustomersTableAdapter.Fill(this.MyDBDataSet.Customers);
You have to call this function after every deletion(Re-bind Grid).
void BindGrid()
{
YourDataGridView.DataSource = dataset;
YourDataGridView.DataBind();
}
I have written the following code to display the fields of my choice in DataGrid. What I want to do is to hide the ID column of COUNTRY table in the DataGrid. So it should not appear to the user. But I also want to still get the ID of COUNTRY table record if the user click on any column or sorts the DataGrid.
Kindly help me. What should I do? What is missing in this code?
OleDbDataAdapter da;
DataSet ds;
public void showGrid()
{
OleDbConnection conn = new OleDbConnection(ConnString);
string sql = #"Select id, country_code, country_name , from country";
OleDbDataAdapter da = new OleDbDataAdapter(sql,conn);
try
{
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Cat");
// Turn this off so column names do not come from data source
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Cat";
dataGridView1.Columns[0].HeaderText = "Code";
dataGridView1.Columns[1].HeaderText = "Name";
dataGridView1.Columns[0].Name = "country_code";
dataGridView1.Columns[1].Name = "country_name";
dataGridView1.Columns[0].DataPropertyName = "country_code" ;
dataGridView1.Columns[1].DataPropertyName = "country_name";
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
Add this line in Form1_Load method
dataGridView1.Columns[0].Visible = false;
Please Mark as Answer, if this solves your problem