Adding a dropdown list from server side - c#

i have this following code :
<asp:DropDownList ID="dd_SubCategory" Width="160px" runat="server" DataTextField="CATEGORY_NAME" DataValueField="CATEGORY_ID"></asp:DropDownList>
<br />
<asp:Panel ID="pnl_SubCatg" runat="server"></asp:Panel>
<asp:ImageButton ID="Ib_AddSubCategory" runat="server" OnClick="Ib_AddSubCategory_Click" ImageUrl="/images/add.gif" />
protected void Ib_AddSubCategory_Click(object sender, ImageClickEventArgs e)
{
string SelectedCategory="";
if (ctrl_list.Count == 0)
SelectedCategory = dd_SubCategory.SelectedValue;
else
SelectedCategory = Session["Selected_SubCatg"] != null && Session["Selected_SubCatg"].ToString()!=""?Session["Selected_SubCatg"].ToString():((DropDownList)ctrl_list[ctrl_list.Count - 1]).SelectedValue;
try
{
DataRow[] Rows = DataHelper.TicketCategories.Select("PARENT_CATEGORY_ID='" + SelectedCategory + "'");
if (Rows.Length > 0)
{
AddSubCategory(Rows);
}
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
catch (Exception ex)
{ }
}
List<Control> _ctrl_list = null;
List<Control> ctrl_list {
get
{
if (Session["SUB_CATG_LIST"] == null)
{
_ctrl_list = new List<Control>();
Session["SUB_CATG_LIST"] = _ctrl_list;
}
return Session["SUB_CATG_LIST"] as List<Control>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["SUB_CATG_LIST"] = null;
Session["Selected_SubCatg"] = null;
}
if (ctrl_list.Count > 0)
{
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
}
private void AddSubCategory(DataRow [] Rows)
{
DropDownList dd_SubCategory1 = new DropDownList();
dd_SubCategory1.Width = Unit.Pixel(160);
dd_SubCategory1.DataTextField = "CATEGORY_NAME";
dd_SubCategory1.DataValueField = "CATEGORY_ID";
dd_SubCategory1.ID = Guid.NewGuid().ToString();
dd_SubCategory1.DataSource = Rows.CopyToDataTable();
dd_SubCategory1.DataBind();
dd_SubCategory1.SelectedIndexChanged += dd_SubCategory1_SelectedIndexChanged;
dd_SubCategory1.AutoPostBack = true;
ctrl_list.Add(dd_SubCategory1);
}
void dd_SubCategory1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Selected_SubCatg"] = ((DropDownList)sender).SelectedValue;
}
i am trying to add a dropdown list containing the subcategories of the last inserted dropdown list , my problem is dd_SubCategory1_SelectedIndexChanged is not firing and i can't get the and the selectedValue of the last dropdownlist is always the same

That is because its dynamically generated and it will lose its state after its rendered on your page.
To access the dropdown and its related events and properties, you will need to recreate it everytime your page is postback.
Hope its clear enough.

Related

Telerik: Unable to get Selected Value of Dropdownlist added to Autogenerated Radgrid

I added a dropdownlist to an auto-generated RadGrid in code behind, however, I am unable to get the selected value when the row is updated. I add the dropdownlist as follows:
protected void grdAssetImport_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem edit = (GridEditableItem)e.Item;
TextBox txt = (TextBox)edit["AssetTypeName"].Controls[0];
txt.Visible = false;
DropDownList rddl = new DropDownList();
PortalView.LookupListBO list = LookupListBA.LookupList_GetByKey(DB_Context, "SITE_ASSETTYPE_LIST", UtilityBA.IsActiveChoice.Active);
List<PortalView.LookupListItemBO> oList = LookupListBA.LookupListItem_GetList_ByLookupListId(DB_Context, list.LookupListId, (Guid)Current.Employee.SiteId);
var AssetList = oList.Select(l => new { AssetTypeName = l.Name });
rddl.ID = "ddlAssetTypeName";
rddl.AutoPostBack = false;
rddl.DataSource = AssetList;
rddl.DataTextField = "AssetTypeName";
rddl.DataValueField = "AssetTypeName";
rddl.DataBind();
edit["AssetTypeName"].Controls.Add(rddl);
}
}
I tried retrieving the selected value in the UpdateCommand, but have been unsuccessful:
protected void grdAssetImport_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
GridEditManager editMan = editedItem.EditManager;
foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
{
GridEditableItem editableItem = e.Item as GridEditableItem;
DropDownList ddl = editableItem.FindControl("ddlAssetTypeName") as DropDownList;
if(ddl != null)
{
string assetType = ddl.SelectedValue;
}
DropDownList ddl2 = editableItem["AssetTypeName"].Controls[0] as DropDownList;
if(ddl2 != null)
{
string assetType = ddl.SelectedValue;
}
if (column is IGridEditableColumn)
{
IGridEditableColumn editableCol = (column as IGridEditableColumn);
if (editableCol.IsEditable)
{
IGridColumnEditor editor = editMan.GetColumnEditor(editableCol);
string editorText = "unknown";
object editorValue = null;
if (editor is GridTextColumnEditor)
{
editorText = (editor as GridTextColumnEditor).Text;
editorValue = (editor as GridTextColumnEditor).Text;
}
if (editor is GridBoolColumnEditor)
{
editorText = (editor as GridBoolColumnEditor).Value.ToString();
editorValue = (editor as GridBoolColumnEditor).Value;
}
if (editor is GridDropDownColumnEditor)
{
editorText = (editor as GridDropDownColumnEditor).SelectedText + "; " +
(editor as GridDropDownColumnEditor).SelectedValue;
editorValue = (editor as GridDropDownColumnEditor).SelectedValue;
}
try
{
DataRow[] changedRows = this.AssetGridDataSource.Select("Id = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["Id"].ToString());
changedRows[0][column.UniqueName] = editorValue;
this.AssetGridDataSource.AcceptChanges();
GetSearchColumns();
}
catch (Exception ex)
{
// Label1.Text = "<strong>Unable to set value of column '" + column.UniqueName + "'</strong> - " + ex.Message;
e.Canceled = true;
break;
}
}
}
}
}
It never finds the dropdownlist, and always only sees the GridTextColumnEditor of the column so the only value I get is the original value before edit mode.
Any assistance is greatly appreciated!
Items do not bind every time and so the ItemDataBound event fires less times than you think. To add a control every time an item is created, you would need to use the ItemCreated event instead.
I've tested the following and works.
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem edititem = e.Item as GridEditableItem;
DropDownList rddl = new DropDownList();
edititem["AssetTypeName"].Controls[0].Visible = false;
rddl.ID = "ddlAssetTypeName";
rddl.AutoPostBack = false;
rddl.DataSource = Enumerable.Range(1, 3).Select(x => "Item" + x).ToList();
rddl.DataBind();
edititem["AssetTypeName"].Controls.Add(rddl);
}
}
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
DropDownList ddl = editedItem["AssetTypeName"].FindControl("ddlAssetTypeName") as DropDownList;
string selectedValue = ddl.SelectedValue;
}

Database Records on Page Load - Dynamic Text Fields

I am working with dynamically created text fields. Most solutions I have found thus far have been related to retaining view state on postback, but I believe I have taken care of that issue. On postback, the values that are in the text fields are retained.
The issue I am having: I can't get the database values currently stored to load in the dynamic fields. I am currently calling loadUpdates() to try to do this, but unsure how to grab the data row, while also making sure I can continue to add new fields (or remove them). How can I achieve this?
"txtProjectsUpdate" is the text field, "hidFKID" is the foreign key to a parent table, and "hidUpdateID" is the hidden value of the primary key in the child table (the values I am attempting to load).
Markup:
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>
<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = selectDetails();
tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());
loadUpdates();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int)count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox
{
ID = string.Concat("txtProjectUpdates", index),
Rows = 5,
Columns = 130,
TextMode = TextBoxMode.MultiLine,
CssClass = "form-control",
MaxLength = 500
});
panel.Controls.Add(new TextBox
{
ID = string.Concat("hidUpdateID", index)
});
var btn = new Button { Text = "Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
placeHolderControls.Controls.Add(panel);
}
protected void loadUpdates()
{
DataTable dt = dbClass.ExecuteDataTable
(
"spSelectRecords", <db>, new SqlParameter[1]
{
new SqlParameter ("#vFKPrjNumber", hidFKID.Value)
}
);
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
{
try
{
hidFKID.Value = txtSelected;
}
catch
{
hidFKID.Value = "";
}
}

right click on linkbutton in gridview is not opening into new tab

I am using a linkbutton within a gridview control.I want to open the link into a new tab. Link button:
<asp:LinkButton ID="lbtnEditCompany" CssClass="ahrefSearch" Text="Select" runat="server" OnClick="lbtnEditCompany_Click" />
Source Code :
protected void lbtnEditCompany_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
SiteID = button.CommandArgument;
DataSet set = DataAccess.GetAllCorporateSites(SearchbyAlphabet, SessionManager.SaleID, SearchbyAssociate);
string str = "";
for (int i = 0; (i < set.Tables[0].Rows.Count) && (str == ""); i++)
{
if (SiteID == set.Tables[0].Rows[i]["ID"].ToString())
{
str = set.Tables[0].Rows[i]["CompanyName"].ToString();
}
}
SessionManager.WidgetId = Convert.ToInt32(SiteID);
SessionManager.SalesPersonSiteName = str;
base.Response.Redirect("~/Corporate/WidgetDetails.aspx", false);
}
catch (Exception exception)
{
HandlePageError(exception);
}
}
Try below code
Response.Write(String.Format("window.open('{0}','_blank')", ResolveUrl("~/Corporate/WidgetDetails.aspx")));

Keep State of Gridview

I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}
You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.

How to delete a selected DataGridViewRow and update a connected database table?

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.

Categories

Resources