Gridview always show previous selected row - c#

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.

Related

Delete a row in DataGridView c# using textbox value

I have created a datagridview that gets all the data from MySQL Workbench database. Below this datagridview, I have created another datagrid with the same columns. For that, I have created a copy function, that on selecting the rows form the first datagridview, copies the selected rows to the second datgrid.
I have then created textboxes that displays the rows that are selected in the second datagridview.
All I want to do now is, get the values from the textboxes, match it in first datagridview, and after clicking on delete button, delete the respected row from first datagridview and respectievely from the database.
I am new to c#, so any help will be appreciated.
Source Code:
namespace panelApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void copy_Click(object sender, EventArgs e)
{
// dataGridView2.Rows.Clear(); (code used if you want to delete previous selections)
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if (item.Selected == true)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = item.Cells[0].Value.ToString();
dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
}
}
}
public void fetch_Click(object sender, EventArgs e)
{
this.productsTableAdapter.Fill(this.productsDataset.products);
productsDataset dt = new productsDataset();
foreach (DataRow item in dt.products.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[1].Value = item["product_id"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["product_name"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["category_id"].ToString();
}
}
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex) // error on this line.
{
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView2.Rows[e.RowIndex];
product_idTxtbx.Text = row.Cells["product_id"].Value.ToString();
proName_txtbx.Text = row.Cells["product_name"].Value.ToString();
catID_txtbx.Text = row.Cells["category_id"].Value.ToString();
}
}
private void delete2_Click(object sender, EventArgs e)
{
// if (dataGridView1.Rows["row.index"].Cells["productidDG"].Value.ToString() == product_idTxtbx.Text)
{
}
}
}
}
On delete button click event btn_OnDelete() find the gridview index then find the all id's by row index.
Then compare each gridview row id to textbox item id
like:
if(GridView1.Rows.Cell[0].Text == TextBox1.tex)
{
// Delete Query here
}
for full solution share code with me.
see here demo link: CRUD Operation link
You should use this code:
<asp:Button ID="delete" runat="server" CommandArgument='<%#Eval("Id") %>' Text="Delete" />
private void delete_btn_Click(object sender, EventArgs e)
{
//incase you need the row index
int rowIndex = ((GridViewRow)((Button)e.CommandSource).NamingContainer).RowIndex;
int Prod_Id= Convert.ToInt32(e.CommandArgument);
//followed by your code
try
{
// Then Compare your Id here in this if condition
// if (dataGridView1.Rows.Cell[0].Text == TextBox1.tex
if (Prod_id == Convert.ToInt32(TextBox1.text)) // error on this line.
{
// User Code Here
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}
please make your code like below
private void delete_btn_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row in dataGridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
if (row.Cell[0].value == TextBox1.tex)
{
//delete opration here for TextBox1.tex/row.Cell[0].Text(Product_id)
break;
}
}
}
}
catch (System.Exception)
{
MessageBox.Show("Not able to Delete");
}
}

How to store previous selected item from `DropDownList`

I have a DropDownList, using which I have to store some values from the CheckBoxList in the database.
Before I select another index from the DropDownList, the values in the CheckBoxList has to be stored, prompting the user with an alert "Save before proceeding".
I am able to display the above mention alert message. But the problem is once i change the index it DropDownList, the previous selected index is lost.
Can someone kindly help me getting the previous selected value and select the same dynamically in DropDownList. Because the value is need to store in database.
The code for displaying alert message is:
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
With the use of Global variables.
Using the code below. PreviousIndex will hold the previous, and CurrentIndex will hold current.
int PreviousIndex = -1;
int CurrentIndex = -1;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
PreviousIndex = CurrentIndex;
CurrentIndex = myDropdownList.Position; // Or whatever the get position is.
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
You can get the selected value first time the page load as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Because When postback occurs the selected valued changed.
{
ViewState["PreviousValue"] = ddl.SelectedValue;
}
}
and in your selected index change event update your previous value by the new value as
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["NewValue"] = ddl.SelectedValue;
// Do your work with PreviousValue and then update it with NewValue so next you can acces your previousValue using ViewState["PreviousValue"]
ViewState["PreviousValue"] = ViewState["NewValue"];
}
or If you want to access selected value on different pages then save it in Session.
you can try with this code - bu using session caching
public string YourOldValue
{
get
{
if(Session["key"] != null)
return (string) Session["key"];
}
set
{
Session["key"] = value;
}
}
//Set value
YourOldValue = yourControl.SelectedValue;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SavedItem"] = LOC_LIST2.SelectedItem;
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
after you access on value or text
SelectedItem item = Session["SavedItem"] as SelectedItem;
if(item !=null)
{
string something= item.Value;
string otherthing =item.Text;
}
So here's what finally worked for me. A combination of the answers above.
You have to track both previous and current selected index/value in the OnLoad handler of the page/control.
private int PreviousSelectedIndex
{
get { return (Page.ViewSate["prevIdx"] == null) ? -1 : (int)ViewSate["prevIdx"]; }
set { Page.ViewSate["prevIdx"] = value; }
}
private int CurrentSelectedIndex
{
get { return (Page.ViewSate["currIdx"] == null) ? -1 : (int)ViewSate["currIdx"]; }
set { Page.ViewSate["currIdx"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
PreviousDropDownValue = ddlYourDropDownList.SelectedValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
else if (Page.IsPostBack && CurrentDropDownValue != ddlYourDropDownList.SelectedValue)
{
PreviousDropDownValue = CurrentDropDownValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
}
After that you can compare the previous and current values with each other.

Sorting Gridview breaks ModalPopUp in GridView

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.

cannot see the label content when a item is selected from dynamically added dropdownlist

I have a Dropdownlist (DDL1) when I select any item from this dropdownlist(DDL1), results in creation of another dropdownlist(DDL2), This contains some of the items.When I select other Item from DDL1 , Items will change in DDL2, this happens for the each different item selected in DDL1.
when I select a item from DDL2, label content must be shown, intially I'm making Label invisibe and in the code I changed the visibility to true and added content to it. But the label content is not shown when I select a item from DDL2.
Here is my Code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Remove("Chacha Choudary");
DropDownSeller.Items.Remove("SpiderMan");
DropDownSeller.Items.Remove("Amar chitra Katha");
DropDownSeller.Items.Remove("Chandamama");
DropDownSeller.Items.Remove("Mahabharata");
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}
Any ideas on this are appreciated
Thanks,
Remove if (!Page.IsPostBack) from the DropDownList1_SelectedIndexChanged because when the page postbacks this condition will be false. Because your page is posting back to the server that's why it is not visible and not showing.
In short your DropDownList1_SelectedIndexChanged should be like..
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue == "Abe Books")
{
DropDownSeller.Visible = true;
lnkUsdBooks.Visible = true;
lnkUsdBooks.Text = "usedbooks#abe.com";
lnkUsdBooks.NavigateUrl = "mailto:usedbook#abe.com";
DropDownSeller.Visible = true;
DropDownSeller.Items.Clear(); // it will clear all the items, instead you are removing one by one
DropDownSeller.Items.Add("Amar chitra Katha");
DropDownSeller.Items.Add("Chandamama");
DropDownSeller.Items.Add("Mahabharata");
DropDownSeller.DataBind();
}
protected void DropDownSeller_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownSeller.SelectedValue == "Amar chitra Katha")
{
lblPrice.Visible = true;
lblPrice.Text = "$69.99";
}
else if (DropDownSeller.SelectedValue == "Chandamama")
{
lblPrice.Visible = true;
lblPrice.Text = "$59.99";
}
else if (DropDownSeller.SelectedValue == "Mahabharata")
{
lblPrice.Visible = true;
lblPrice.Text = "$49.99";
}
else
{
lblPrice.Visible = false;
}
}

checking if gridview has a selected item

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;
}

Categories

Resources