I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.
My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load
I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load?
Here is the code for the modalpopup, gridview binding and sorting.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["sortOrder"] = "";
Bind_Gridview("", "");
loadModals();
}
}
protected void viewModal(object sender, EventArgs e)
{
...
mainPanel.Controls.Add(exstModal);
mainPanel.Controls.Add(exstModalBox);
exstModalBox.Show();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
Bind_Gridview(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void gv1_RowCommand(object sender, GridViewRowEventArgs e)
{
...
CheckBox cb = new CheckBox();
TextBox ca = new TextBox();
ca.Width = 20;
TextBox cga = new TextBox();
cga.Width = 20;
if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview
{
while (dr1.Read())
{
ca.Text = dr1["cyla"].ToString();
cga.Text = dr1["cga"].ToString();
checkText = dr1["completed"].ToString();
if (checkText == "True")
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
}
...
dr1.Close();
conn1.Close();
e.Row.Cells[6].Controls.Add(ca);
e.Row.Cells[8].Controls.Add(cga);
e.Row.Cells[9].Controls.Add(cb);
...
}
A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState.
Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.
I have a grideview and 2 buttons. I need to only show the buttons when the gridview has a selected item. My code looks like this:
protected void Page_Load(object sender, EventArgs e)
{
btactivate.Visible = false;
btdeactivate.Visible = false;
//Show Activate and Deactivate Buttons only if an item in the gridview is selected
if (GridView1.SelectedIndex != -1)
{
btactivate.Visible = true;
btdeactivate.Visible = true;
}
else
{
btactivate.Visible = false;
btdeactivate.Visible = false;
}
}
But the problem I have now is that only when I select the second time a item in the gridview the buttons show up. I need to have the the buttons show when I select the first time. I have tried changing the selected index to "-0" but that shows the buttons all the time (even when I dont have something selected). Can anyone please help?
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
dt.Columns.Add("Col3");
for (int i = 0; i < 20; i++)
{
DataRow dr = dt.NewRow();
dr["Col1"] = string.Format("Row{0}Col1", i + 1);
dr["Col2"] = string.Format("Row{0}Col2", i + 1);
dr["Col3"] = string.Format("Row{0}Col3", i + 1);
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
SetButtonState();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
SetButtonState();
}
private void SetButtonState()
{
btactivate.Visible = GridView1.SelectedIndex > -1;
btdeactivate.Visible = GridView1.SelectedIndex > -1;
}
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.