Delete selected row - c#

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;

Related

DataGridView add column by code

I need to add columns to my DataGridView dynamically... to do this here is my code:
dgv.Columns.Clear();
dgv.AutoGenerateColumns = false;
for (int i = 0; i < fields.Length; i++)
{
var newColumn = new DataGridViewColumn(new DataGridViewTextBoxCell());
newColumn.Name = fields[i];
newColumn.DataPropertyName = fields[i];
newColumn.HeaderText = fields[i];
dgv.Columns.Add(newColumn);
}
And after, when I link my query to the DataSource I retrieve this error:
The value can't be null.
Parameter name: columnName
And the strange thing is that here is my DataGridView/DataTable situation:
The names seems right...
The other strange thing is that the first row is shown, but the others gives the exception (the query is OK and the data are valid...)
here is the code to create the DataSource for the table:
public DataTable getData()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(item.Query, db.getConnection());
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
dap.Fill(ds);
return ds.Tables[0];
}
and after:
dgv.DataSource = getData();

Get string value of the GridView cell on click

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;

How clear GridView in asp.net?

I doing a web page in asp.net and in a module have select a Excel archive with FileUpLoad and click in a button import. Hitherto I'm fine. But in the moment than I want select other Excel archive and click in the button import, don't clear the GridView and show error. I attempt with this because I see in other questions similar to this.
With this I load the Grid
Conn = string.Format(Conn, DireccionArchivo, MostrarHDR);
OleDbConnection ConnExcel = new OleDbConnection(Conn);
OleDbCommand CmdExcel = new OleDbCommand();
OleDbDataAdapter Oda = new OleDbDataAdapter();
DataTable Dt = new DataTable();
CmdExcel.Connection = ConnExcel;
ConnExcel.Open();
CmdExcel.CommandText = "SELECT * From ["Page1$"]";
Oda.SelectCommand = CmdExcel;
Oda.Fill(Dt);
ConnExcel.Close();
grdResultados.Caption = Path.GetFileName(DireccionArchivo);
grdResultados.DataSource = Dt;
grdResultados.DataBind();
And with this I want to clear the GridView and last y called of new the method of load the GridView
DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;
grdResultados.DataBind();
The error than show me is in the grdResultados.DataBind(); when called the second time.
Just use null value:
grdResultados.DataSource = null;
grdResultados.DataBind();
I resolved the problem, in the moment than clear the GridView with
DataTable ds = new DataTable();
ds = null;
grdResultados.DataSource = ds;
grdResultados.DataBind();
this clear the GridView but dont clear the names of columns, and this was the error, also have to clean the names of the columns. To remove the columns:
for (int i = 0; grdResultados.Columns.Count > i; )
{
grdResultados.Columns.RemoveAt(i);
}
and in the method of load th GridView must be generate the columns automatically with this property:
grdResultados.AutoGenerateColumns = true;
I leave this in case anyone else has the same problem
try this
grdResultados.DataSource = null;
or
grdResultados.Rows.Clear();
then rebind the gridview
int gvHasRows = grdResultados.Rows.Count;
if (gvHasRows > 0)
{
grdResultados.Columns.Clear();
grdResultados.DataBind();
}
First check that there is data in the Gridview before trying to clear.
Rows has no Clear function.
If you use a Session clear the session Example:
DataTable ds = new DataTable();
ds = null;
GV.DataSource = ds;
GV.DataBind();
for (int i = 0; GV.Columns.Count > i; )
{
GV.Columns.RemoveAt(i);
}
ViewState["CurrentData"] = null;
Make an empty data table with just your column names and re bind
You can simply do this:
GridView1.SelectedIndex = -1;
If dataset IsNot Nothing AndAlso dataset.Tables.Count > 0 AndAlso dataset.Tables(0).Rows.Count > 0 Then
grid.DataSource = dataset
grid.DataBind()
Else
grid.DataSource = Nothing
grid.DataBind()
If you're using a XAML defined Grid, use this instead:
GridView1.Children.Clear();
GridView1.RowDefinitions.Clear();
GridView1.ColumnDefinitions.Clear();

How to show dataset changes in datagridview?

I have a code like below.
I a dataset and two tables in it. And there is a relation between those tables.
DataSet ds = new DataSet();
DataTable dtPerson = new DataTable("Persons");
DataTable dtBooks = new DataTable("Books");
ds.Tables.Add(dtPerson);
ds.Tables.Add(dtBooks);
dtPersons = LoadPersons();
dtBooks = LoadBooks();
ds.Relations.Add(new DataRelation("PersonBookRel",dtPersons.Columns["P_ID"],dtBooks.Columns["P_ID"]));
gridPersons.DataSource = ds;
gridPersons.DataMember = "Persons";
gridBooks.DataSource = ds;
gridBooks.DataMember = "Books";
The problem is that, when i add new row to dtPerson, gridPerson does not show new records.
Code is below.
DataRow row = dtPerson.NewRow();
row[0] = "Joe";
row[1] = "Black"
row[2] = 18;
...
dtPerson.Rows.Add(row);
ds.AcceptChanges();
So what is the problem? How to solve it?

Modifying a column in DGV to be a Combobox Bound to DataBase

I created a view named "FamilyView" to join 2 tables(Families and SStatus) and replace an id in the first table(Families) by its name existing in the second table(SStatus) (the column is now called "Status")
This view is now displayed in a datagridview that the user can modify
Sda = new SqlDataAdapter("Select * from FamilyView",con);
Sda.Fill(ds);
dg.DataSource = ds.Tables[0];
dg.Refresh();
What i want is to transform the column cells "Status" to comboboxes containing all Names from SStatus
SqlDataAdapter sadapter = new SqlDataAdapter("Select * From SStatus", con);
DataSet ds1 = new DataSet();
sadapter.Fill(ds1);
i found this code:
DataGridViewComboBoxCell ComboColumn = (DataGridViewComboBoxCell)(dg.Rows[i].Cells[0]);
ComboColumn.DataSource = ds1.Tables[0];
ComboColumn.DisplayMember = "Name";
but i can't replace the cell
and this code but I'm not sure how to use it:
Adding bound combobox to datagridview
BindingSource StatusBD = new BindingSource();
StatusBD.DataSource = ds1;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Status";
colType.DropDownWidth = 90;
colType.Width = 90;
//colType.DataPropertyName = "Name";
colType.DataSource = ds;
colType.DisplayMember = "Name";
colType.ValueMember = "IdStatus";
dg.Columns.Insert(dg.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
Your data source is empty: it should contain 2 tables: one with the SStatus and one with Families.
and then follow my as in your post:
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol"; // This is the table in the set
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols"
Here idProtocol (which is referenced as protocol in the "pcap" table) is mapped to protocolName.

Categories