I am trying to add the column names of a gridview to a dropdown list.
The problem is when I change the datasource of the gridview, it returns empty.
I am not sure whether the event is working properly, as it does not work with/without it.
I wanted to use the DataBindComplete event, but I could not see it so I tried DataBound instead.
private void BindTable()
{
if (ddTableSearch.SelectedIndex == 0)
{
tblCustomerTableAdapter customerAdapter = new tblCustomerTableAdapter();
GridView2.DataSource = customerAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 1)
{
tblInvoiceTableAdapter invoiceAdapter = new tblInvoiceTableAdapter();
GridView2.DataSource = invoiceAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 2)
{
tblEstimateTableAdapter estimateAdapter = new tblEstimateTableAdapter();
GridView2.DataSource = estimateAdapter.GetData();
GridView2.DataBind();
}
}
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
ddColumnSearch.Items.Clear();
for (int i = 0; i < GridView2.Columns.Count; i++)
{
ddColumnSearch.Items.Add(new ListItem(GridView2.Columns[i].ToString()));
}
}
What am I doing wrong?
The databound event runs for each record in the gridview. So one issue is that each time you are clearing out the items you added before. Another issue is that you need to get the data from the EventArgs instead of from the gridview.columns since those are not there until after all the data is bound. I think all you need to do is get the data from the header row:
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
if(e.Row.RowType != DataControlRowType.Header) return; //only continue if this is hdr row
ddColumnSearch.Items.Clear();
foreach (TableCell cell in e.Row.Cells)
{
ddColumnSearch.Items.Add(new ListItem(cell.Text));
}
}
I have a page with a gridview (actually two, but they are identical and the same thing happens with either).
New rows are added to the gridview from the footerrow via a link button.
When using the page to edit existing data, a strange thing happens. When I create the page in edit mode (i.e. to add/remove rows from an existing set of data in the table) the first time I try to add another row to the gridview, the IsPostBack is set to false and thus the gridviews re-initialise / rebind and my change is lost. The second and further time that I try to add rows, it works fine as the PostBack is recognised.
What could be causing the PostBack not to be recognised as one?
I'm not sure it's worth posting code but I will post my Page_Load for what it is worth:
querystring:
a=n is "new" (for creating a page to add a new set of records)
a=e is "edit" (populate page with existing data to allow for adding / removing rows.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
String action = Request.QueryString["a"];
if (action == "n")
{
BindBuyGrid("create");
BindSellGrid("create");
}
else if(action == "e")
{
PopulatePage();
}
}
}
Update 1
protected void gvwBuyConditions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "InsertNew")
{
AddNewRowToBuyConditionsGrid();
}
}
Update 2
The link button code. Surely this should trigger a postback?
<FooterTemplate>
<asp:LinkButton
ID="lnkInsert"
runat="server"
CommandName="InsertNew"
ToolTip="Add New Entry to List" >
<img src="../Images/Add.ico" height="20" width="20"/></asp:LinkButton>
</FooterTemplate>
Update 3
The AddNewRowToBuyConditionsGrid code:
private void AddNewRowToBuyConditionsGrid()
{
if (ViewState["BuyConditions"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["BuyConditions"];
DataRow drCurrentRow;
GridViewRow row = gvwBuyConditions.FooterRow;
DropDownList ddlSelectedCondition = row.FindControl("ddlConditionNew") as DropDownList;
try
{
if (ddlSelectedCondition.Text != "Select a Buy Condition")
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["ConditionName"] = ddlSelectedCondition.SelectedItem.Text;
drCurrentRow["ConditionID"] = Convert.ToInt32(ddlSelectedCondition.SelectedItem.Value);
dtCurrentTable.Rows.Add(drCurrentRow);
drCurrentRow = null;
}
// take out the dummy "Select a Condition"
DataRow drtodie = dtCurrentTable.Rows.Find(-1);
if (drtodie != null)
{
dtCurrentTable.Rows.Find(-1).Delete();
}
//Store the current data to ViewState
ViewState["BuyConditions"] = dtCurrentTable;
//Rebind the Grid with the current data
gvwBuyConditions.DataSource = dtCurrentTable;
gvwBuyConditions.DataBind();
}
catch (Exception)
{
if (ddlSelectedCondition.SelectedItem.Value == String.Empty)
{
lblBuyMessage.Text = "Please select a Buy Condition.";
}
else
{
lblBuyMessage.Text = "That condition already exists in the list. Please select another condition.";
}
}
}
else
{
Response.Write("ViewState is null");
}
}
Update 4
Code on previous page that calls this page. e is just configured in string. Is it maybe the Server.Transfer?
protected void gvwStrategyList_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UseEditForm")
{
//row index
int index = Convert.ToInt32(e.CommandArgument);
//retrieve StrategyID
int StrategyID = Convert.ToInt32(gvwStrategyList.DataKeys[index].Value);
Server.Transfer("~/AddStrategy.aspx?a=e&z=" + StrategyID, true);
}
}
Hello fellow programmers,
Right now I have a webpage which displays a data-table via grid-view. This works fine. I also inserted a column of check-boxes in the beginning of the view. This works fine as well. But when I try to retrieve info from cells from the row whose respective check-box is selected, I get an empty string.
Below are the parts of my code pertinent to this problem:
.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
else
{
}
//server connections and whatnot//
OleDbCommand c0 = new OleDbCommand(sql0, myConnection);
myAdapter.SelectCommand = c0;
DataSet ds0 = new DataSet("Contacts");
myAdapter.Fill(ds0);
DataTable dt0 = new DataTable();
dt0 = ds0.Tables["Contacts"];
DataView view = new DataView();
view.Table = dt0;
GV0.DataSource = view;
GV0.DataBind();
myConnection.Close();
}
.cs:
/**
* WHY U NO WORK?!
*/
public void Dedupe(Object o, EventArgs e)
{
String output = "start ";
foreach (GridViewRow row in GV0.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.Checked == true)
{
output += row.Cells[1];
}
}
Label1.Text = output;
}
Any help would be greatly appreciated.
Cheers
Just a thought but in your foreach loop you may need to check the RowType property of the current row that you are looping over and make sure that it is set to DataRow. Or you could use a LINQ statement to bring back only rows with a RowType == DataRow and loop over that.
UPDATE Here is a quick sample of what I meant. But in reviewing your code it does not appear that you have any text in the second cell of your gridview, in fact your gridview only has one cell based on the code you provided.
public void Dedupe(Object o, EventArgs e)
{
String output = "start ";
IEnumerable<GridViewRow> rows = from r in GV0.Rows
where r.RowType == DataControlRowType.DataRow
select r;
foreach (GridViewRow row in rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb.Checked)
{
output += row.Cells[1];
}
}
Label1.Text = output;
}
I want the user to be able to search for a number in a column in the DataGridView (dgv). The dgv can hold many records. Each record has a Project Number. So I want the user to be able to search for a project number in column Project Number. The columns I have are: ProjectID(not visible); Image(no headertext); Project Number; Project Name; Company; Contact.
Here is my code:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
int rowIndex = -1;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[row.Index].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dgvProjects.Rows[row.Index].Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Problem #1: What it does so far: The user types the project number in TextBox1. When he/she clicks the button, the code searches for this string in the rows, and when found the project number, that row gets selected. It works fine, but only once. When I want to search for an other project number, nothing happens.
Problem #2: I think this can be done in a better way, by searching the values for column Project Name only. But how should I do this properly?
The code I used to search comes from this answer
Why you are using row.Cells[row.Index]. You need to specify index of column you want to search (Problem #2). For example, you need to change row.Cells[row.Index] to row.Cells[2] where 2 is index of your column:
private void btnSearch_Click(object sender, EventArgs e)
{
string searchValue = textBox1.Text;
dgvProjects.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
foreach (DataGridViewRow row in dgvProjects.Rows)
{
if (row.Cells[2].Value.ToString().Equals(searchValue))
{
row.Selected = true;
break;
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Why don't you build a DataTable first then assign it to the DataGridView as DataSource:
DataTable table4DataSource=new DataTable();
table4DataSource.Columns.Add("col00");
table4DataSource.Columns.Add("col01");
table4DataSource.Columns.Add("col02");
...
(add your rows, manually, in a circle or via a DataReader from a database table)
(assign the datasource)
dtGrdViewGrid.DataSource = table4DataSource;
and then use:
(dtGrdViewGrid.DataSource as DataTable).DefaultView.RowFilter = "col00 = '" + textBoxSearch.Text+ "'";
dtGrdViewGrid.Refresh();
You can even put this piece of code within your textbox_textchange event and your filtered values will be showing as you write.
It's better also to separate your logic in another method, or maybe in another class.
This method will help you retreive the DataGridViewCell object in which the text was found.
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}
// This is the exact code for search facility in datagridview.
private void buttonSearch_Click(object sender, EventArgs e)
{
string searchValue=textBoxSearch.Text;
int rowIndex = 1; //this one is depending on the position of cell or column
//string first_row_data=dataGridView1.Rows[0].Cells[0].Value.ToString() ;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResulet = true;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[rowIndex].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
rowIndex++;
valueResulet = false;
}
}
if (valueResulet != false)
{
MessageBox.Show("Record is not avalable for this Name"+textBoxSearch.Text,"Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
Filter the data directly from DataTable or Dataset:
"MyTable".DefaultView.RowFilter = "<DataTable Field> LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
Use this code on event KeyUp of Textbox, replace "MyTable" for you table name or dataset, replace for the field where you want make the search.
"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'";
this.dataGridView1.DataSource = "MyTable".DefaultView;
How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?
I use this code to get the data out:
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();
DataTable dt = new DataTable();
adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
string searchValue = txtSearch.Text;
string colName = dataGridView1.Columns[1].Name;//Column Number of Search
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(colName+" like '%{0}%'", searchValue.Trim().Replace("'", "''"));
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
btnSearch_Click(null,null);
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
string searchValue = txtSearch.Text;
for (var i = 0; i <= dgvList.RowCount; i++)
{
for (var j = 0; j <= dgvList.ColumnCount; j++)
{
if ((dgvList.Item(j, i).FormattedValue.ToString.ToLower).ToString.Contains(searchValue.ToString.ToLower))
{
Console.Writeline("found");
dgvList.Item(j, i).Selected = true;
return;
}
}
}
}
This method will search all rows and cells in the DataGridView, If result is true then select the row.
I'm can solve it simply:
public static int SearchDGV(DataGridView dgv, string SearchValue, string ColName)
{
foreach (DataGridViewRow Row in dgv.Rows)
{
if (Row.Cells[ColName].Value.ToString().Equals(SearchValue))
return Row.Index;
}
return -1;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
DataView dv = ds.Tables["todo"].DefaultView;
dv.RowFilter = "topic LIKE '" + textBox3.Text + "%'";
dataGridView1.DataSource = dv;
}
I have a DataGridView control on a Windows Forms application (written with C#).
What I need is: when a user selects a DataGridViewRow, and then clicks on a 'Delete' button, the row should be deleted and next, the database needs to be updated using table adapters.
This is what I have so far:
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
}
}
Furthermore, this only deletes one row. I would like it where the user can select multiple rows.
This code removes selected items of dataGridView1:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
}
private void buttonRemove_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
}
}
Removes rows which indexes are in selected cells. So, select any cells, and their corresponding rows will be removed.
I have written the following code, please take a look:
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
if (!row.IsNewRow) dataGridView1.Rows.Remove(row);
using the Index of the selected row still could work; see if the code below will do the trick:
int selectedCount = dataGridView1.SelectedRows.Count;
while (selectedCount > 0)
{
if (!dataGridView1.SelectedRows[0].IsNewRow)
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
selectedCount--;
}
I hope this helps, regards.
private void btnDelete_Click(object sender, EventArgs e)
{
if (e.ColumIndex == 10)// 10th column the button
{
dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]);
}
}
This solution can be delete a row (not selected, clicked row!) via "e" param.
maybe you can use temp list for delete. for ignore row index change
<pre>
private void btnDelete_Click(object sender, EventArgs e)
{
List<int> wantdel = new List<int>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((bool)row.Cells["Select"].Value == true)
wantdel.Add(row.Index);
}
wantdel.OrderByDescending(y => y).ToList().ForEach(x =>
{
dataGridView1.Rows.RemoveAt(x);
});
}
</pre>
To delete multiple rows in datagrid, c#
parts of my code:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in datagrid1.SelectedRows)
{
//get key
int rowId = Convert.ToInt32(row.Cells[0].Value);
//avoid updating the last empty row in datagrid
if (rowId > 0)
{
//delete
aController.Delete(rowId);
//refresh datagrid
datagrid1.Rows.RemoveAt(row.Index);
}
}
}
public void Delete(int rowId)
{
var toBeDeleted = db.table1.First(c => c.Id == rowId);
db.table1.DeleteObject(toBeDeleted);
db.SaveChanges();
}
private: System::Void button9_Click(System::Object^ sender, System::EventArgs^ e)
{
String^ constring = L"datasource=localhost;port=3306;username=root;password=password";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
conDataBase->Open();
try
{
if (MessageBox::Show("Sure you wanna delete?", "Warning", MessageBoxButtons::YesNo) == System::Windows::Forms::DialogResult::Yes)
{
for each(DataGridViewCell^ oneCell in dataGridView1->SelectedCells)
{
if (oneCell->Selected) {
dataGridView1->Rows->RemoveAt(oneCell->RowIndex);
MySqlCommand^ cmdDataBase1 = gcnew MySqlCommand("Delete from Dinslaken_DB.Configuration where Memory='ORG 6400H'");
cmdDataBase1->ExecuteNonQuery();
//sda->Update(dbdataset);
}
}
}
}
catch (Exception^ex)
{
MessageBox::Show(ex->ToString());
}
}
Well, this is how I usually delete checked rows by the user from a DataGridView, if you are associating it with a DataTable from a Dataset (ex: DataGridView1.DataSource = Dataset1.Tables["x"]), then once you will make any updates (delete, insert,update) in the Dataset, it will automatically happen in your DataGridView.
if (MessageBox.Show("Are you sure you want to delete this record(s)", "confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
{
try
{
for (int i = dgv_Championnat.RowCount -1; i > -1; i--)
{
if (Convert.ToBoolean(dgv_Championnat.Rows[i].Cells[0].Value) == true)
{
Program.set.Tables["Champ"].Rows[i].Delete();
}
}
Program.command = new SqlCommandBuilder(Program.AdapterChampionnat);
if (Program.AdapterChampionnat.Update(Program.TableChampionnat) > 0)
{
MessageBox.Show("Well Deleted");
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
have a look this way:
if (MessageBox.Show("Sure you wanna delete?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
bindingSource1.RemoveAt(item.Index);
}
adapter.Update(ds);
}
Try this:
if (dgv.SelectedRows.Count>0)
{
dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
}
if(this.dgvpurchase.Rows.Count>1)
{
if(this.dgvpurchase.CurrentRow.Index<this.dgvpurchase.Rows.Count)
{
this.txtname.Text = this.dgvpurchase.CurrentRow.Cells[1].Value.ToString();
this.txttype.Text = this.dgvpurchase.CurrentRow.Cells[2].Value.ToString();
this.cbxcode.Text = this.dgvpurchase.CurrentRow.Cells[3].Value.ToString();
this.cbxcompany.Text = this.dgvpurchase.CurrentRow.Cells[4].Value.ToString();
this.dtppurchase.Value = Convert.ToDateTime(this.dgvpurchase.CurrentRow.Cells[5].Value);
this.txtprice.Text = this.dgvpurchase.CurrentRow.Cells[6].Value.ToString();
this.txtqty.Text = this.dgvpurchase.CurrentRow.Cells[7].Value.ToString();
this.txttotal.Text = this.dgvpurchase.CurrentRow.Cells[8].Value.ToString();
this.dgvpurchase.Rows.RemoveAt(this.dgvpurchase.CurrentRow.Index);
refreshid();
}
}
You delete first from the database and then you update your datagridview:
//let's suppose delete(id) is a method which will delete a row from the database and
// returns true when it is done
int id = 0;
//we suppose that the first column in the datagridview is the ID of the ROW :
foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
id = Convert.ToInt32(row.Cells[0].Value.ToString());
if(delete(id))
this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//else show message error!
private void btnDelete_Click(object sender, EventArgs e)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
?BindingSource.EndEdit();
?TableAdapter.Update(this.?DataSet.yourTableName);
}
//NOTE:
//? - is your data from database
Exception no need ... or change with your own code.
CODE:
DB:
Example: prntscr.com/p3208c
DB Set: http://prntscr.com/p321pw
ArrayList bkgrefs = new ArrayList();
foreach (GridViewRow rowd in grdOptionExtraDetails.Rows)
{
CheckBox cbf = (CheckBox)rowd.Cells[1].FindControl("chkbulk");
if (cbf.Checked)
{
rowd.Visible = true;
bkgrefs.Add(Convert.ToString(grdOptionExtraDetails.Data.Rows[rowd.RowIndex]["OptionID"]));
}
else
{
grdOptionExtraDetails.Data.Rows.RemoveAt(rowd.DataItemIndex);
rowd.Visible = false;
}
}
Try this:
foreach (DataGridViewRow item in this.YourGridViewName.SelectedRows)
{
string ConnectionString = (#"Data Source=DESKTOPQJ1JHRG\SQLEXPRESS;Initial Catalog=smart_movers;Integrated Security=True");
SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("DELETE FROM TableName WHERE ColumnName =#Index", conn);
cmd.Parameters.AddWithValue("#Index", item.Index);
int i = cmd.ExecuteNonQuery();
if (i != 0)
{
YourGridViewName.Rows.RemoveAt(item.Index);
MessageBox.Show("Deleted Succefull!", "Great", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("Deleted Failed!", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This worked for me :
private void btnRemove_Click(object sender, EventArgs e) {
int count = dgvSchedule.SelectedRows.Count;
while (count != 0) {
dgvSchedule.Rows.RemoveAt(dgvSchedule.SelectedRows[0].Index);
count--;
}
}
this command delete selected row when user selected in datagridview:
gvTest.Rows.RemoveAt(dvTest.CurrentRow.Index];
for (int j = dataGridView1.Rows.Count; j > 0 ; j--)
{
if (dataGridView1.Rows[j-1].Selected)
dataGridView1.Rows.RemoveAt(j-1);
}
It Work for me !
private: System::Void MyButton_Delete_Click(System::Object^ sender, System::EventArgs^ e) {
// Удалить столбец(Row).
MydataGridView->Rows->RemoveAt(MydataGridView->CurrentCell->RowIndex);
}
here is one very simple example:
ASPX:
<asp:GridView ID="gvTest" runat="server" SelectedRowStyle-BackColor="#996633"
SelectedRowStyle-ForeColor="Fuchsia">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdateClick"/>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
private readonly DataTable _dataTable;
public _Default()
{
_dataTable = new DataTable();
_dataTable.Columns.Add("Serial", typeof (int));
_dataTable.Columns.Add("Data", typeof (string));
for (var i = 0; ++i <= 15;)
_dataTable.Rows.Add(new object[] {i, "This is row " + i});
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
gvTest.DataSource = _dataTable;
gvTest.DataBind();
}
protected void btnUpdateClick(object sender, EventArgs e)
{
if (gvTest.SelectedIndex < 0) return;
var r = gvTest.SelectedRow;
var i = r.DataItemIndex;
//you can get primary key or anyother column vlaue by
//accessing r.Cells collection, but for this simple case
//we will use index of selected row in database.
_dataTable.Rows.RemoveAt(i);
//rebind with data
BindData();
//clear selection from grid
gvTest.SelectedIndex = -1;
}
}
you will have to use checkboxes or some other mechanism to allow users to select multiple rows and then you can browse the rows for ones with the checkbox checked and then remove those rows.