I have a gridview and it will maintain checkboxes state while paging in gridview.why the checkboxes will still maintain when i refresh the page?how to disable the checkboxes state maintain after i refresh the page or submit data to database?
private void savechkdvls()
{
ArrayList usercontent = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in GrdRole.Rows)
{
index = Convert.ToInt32(GrdRole.DataKeys[gvrow.RowIndex].Value);
bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
if (Session["chkditems"] != null)
usercontent = (ArrayList)Session["chkditems"];
if (result)
{
if (!usercontent.Contains(index))
usercontent.Add(index);
}
else
usercontent.Remove(index);
}
if (usercontent != null && usercontent.Count > 0)
Session["chkditems"] = usercontent;
}
private void chkdvaluesp()
{
ArrayList usercontent = (ArrayList)Session["chkditems"];
if (usercontent != null && usercontent.Count > 0)
{
foreach (GridViewRow gvrow in GrdRole.Rows)
{
int index = Convert.ToInt32(GrdRole.DataKeys[gvrow.RowIndex].Value);
if (usercontent.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
if (!IsPostBack)
{
filldropdown();
Bind();
}
You're able to use
ViewState.Clear();
Response.Redirect("~/PageXXX.aspx");
to clear the ViewState
Related
I want to create a function that will check if the quantity inserted is greater than the new stock in my Datagridview Cell ["New Stock"] to prevent the data from execution.
double qty,totalprice,discount;
double.TryParse(txtqty.Text, out qty);
double.TryParse(txttotalprice1.Text, out totalprice);
double.TryParse(txtdiscount.Text, out discount);
//Boolean to check if he has row has been
bool Found = false;
if (dataGridView1.Rows.Count > 0)
{
// Check if the product Id exists with the same Price
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToString(row.Cells[0].Value) == cmbproductcode.Text && Convert.ToString(row.Cells[3].Value) == txtprice1.Text)
{
//Update the Quantity of the found row
row.Cells[5].Value = Convert.ToString(qty + Convert.ToInt16(row.Cells[5].Value));
row.Cells[7].Value = Convert.ToString(discount + Convert.ToInt16(row.Cells[7].Value)); //txtqty
row.Cells[8].Value = Convert.ToString(totalprice + Convert.ToInt32(row.Cells[8].Value)); //txttotalprice
Found = true;
getprice();
}
}
if (!Found)
{
//Add the row to grid view
getinfo();
}
}
else
{
//Add the row to grid view for the first time
getinfo();
}
public double prev;
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
string cellValue;
int i = e.RowIndex;
cellValue = dataGridView1.Rows[i].Cells[1].Value.ToString();
prev = Convert.ToDouble(cellValue);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string cellValue;
int i = e.RowIndex;
cellValue = dataGridView1.Rows[i].Cells[1].Value.ToString();
double cur = Convert.ToDouble(cellValue);
if(isvalid(prev,cur))
dataGridView1.Rows[i].Cells[1].Value = prev.ToString();
else
dataGridView1.Rows[i].Cells[1].Value = cellValue;
}
private Boolean isvalid(double pr,double cur)
{
return cur > pr ? false : true;
}
I don't know if I am allowed to post such a specific issue here.
The scenario is that I have a Product that has a many to many relationship with Category.
Means one product may belong to multiple categories and a category may have multiple products. Now on the form I have provide a dropdown along with a button that says add another category and when I click on that button another dropdown should appear below that first dropdown. and the selected item of the previous dropdown must be remove from the dropdown items.
Below is my code of the dropdown's repeater and the two buttons mentioned.
protected void btnAddAnotherCategory_Click(object sender, EventArgs e)
{
List<int> selectedIndices = new List<int>();
foreach (RepeaterItem item in rptCategories.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
int selectedIndex = ddlCategory.SelectedIndex;
selectedIndices.Add(selectedIndex);
}
}
ViewState["objSelectedIndices"] = selectedIndices;
rptCategories_DataSource("add", false);
}
protected void btnRemoveCategory_Click(object sender, EventArgs e)
{
List<int> selectedIndices = new List<int>();
foreach (RepeaterItem item in rptCategories.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlCategory = (DropDownList)item.FindControl("ddlCategory");
int selectedIndex = ddlCategory.SelectedIndex;
selectedIndices.Add(selectedIndex);
}
}
ViewState["objSelectedIndices"] = selectedIndices;
rptCategories_DataSource("remove", false);
}
protected void rptCategories_DataSource(string editCommand, bool pageLoad)
{
switch (editCommand)
{
case "add":
if (ViewState["categoriesCount"] == null)
{
List<Category> count = new List<Category>();
count.Add(new Category());
ViewState["categoriesCount"] = count;
}
if (!pageLoad)
{
List<Category> count = (List<Category>)ViewState["categoriesCount"];
count.Add(new Category());
ViewState["categoriesCount"] = count;
}
List<Category> objCategories = (List<Category>)ViewState["categoriesCount"];
objCategories = objCategories.Where(x => x.StatusID != 3).ToList();
rptCategories.DataSource = objCategories;
rptCategories.DataBind();
break;
case "remove":
if (((List<Category>)ViewState["categoriesCount"]).Count > 1)
{
List<Category> count = (List<Category>)ViewState["categoriesCount"];
count.Remove(count.Last());
count = count.Where(x => x.StatusID != 3).ToList();
ViewState["categoriesCount"] = count;
rptCategories.DataSource = count;
rptCategories.DataBind();
}
break;
}
}
protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Category objCategory = (Category)e.Item.DataItem;
DropDownList ddlCategory = (DropDownList)e.Item.FindControl("ddlCategory");
ddlCategory.DataSource = new CategoryBLL().GetAllCategoriesWithStatus();
ddlCategory.DataTextField = "Name";
ddlCategory.DataValueField = "ID";
ddlCategory.DataBind();
if (objCategory.CategoryID != null)
ddlCategory.SelectedValue = objCategory.CategoryID.ToString();
if (ViewState["objSelectedIndices"] != null)
{
List<int> objSelectedIndices = (List<int>)ViewState["objSelectedIndices"];
if (objSelectedIndices.Count > e.Item.ItemIndex)
ddlCategory.SelectedIndex = objSelectedIndices.ElementAt(e.Item.ItemIndex);
}
if (e.Item.ItemIndex < ((List<Category>)rptCategories.DataSource).Count - 1)
{
ddlCategory.Enabled = false;
}
btnAddAnotherCategory.Visible = true;
btnRemoveCategory.Visible = true;
if (rptCategories.Items.Count < 1)
{
btnRemoveCategory.Visible = false;
}
if (rptCategories.Items.Count >= new CategoryBLL().GetAllCategoriesWithStatus().Count - 1)
{
btnAddAnotherCategory.Visible = false;
}
}
The StatusID mentioned in the code is to determine the deleted products as I am not ACTUALLY deleting the Product rather only setting its StatusID
Now the problem is that my code works fine with the above statements but as you can see it does not remove the selected items from the dropdown. The dropdown's are required to be populated from a single table everytime. The tricky part is removing the selecteditems in the previous repeateritems dropdownlist.
Any solution would be welcomed.
How do I force only a single checkbox to be checked in a column of a Datagridview?
private void grdRegClass_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (grdRegClass.Columns.IndexOf(grdRegClass.Columns["Status"]) == e.ColumnIndex)
{
int currentcolumnclicked = e.ColumnIndex;
int currentrowclicked = e.RowIndex;
foreach (DataGridViewRow dr in grdRegClass.Rows)
{
dr.Cells[currentcolumnclicked].Value = false;
}
grdRegClass.CurrentRow.Cells[currentrowclicked].Value = true;
}
}
You will have to subscribe for the CellValueChanged event of the grid and depending on the check state of the current cell, loop the DataGridView and set true/false as Value for the other cells.
void grd_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
{
if (Convert.ToBoolean(((sender as DataGridView).CurrentCell as DataGridViewCheckBoxCell).Value))
{
// Maybe have a method which does the
//loop and set value except for the current cell
}
}
}
private void dataGridViewProduit_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
{
if (Convert.ToBoolean(((sender as DataGridView).CurrentCell as DataGridViewCheckBoxCell).Value))
{
foreach (DataGridViewRow row in (sender as DataGridView).Rows)
{
if (row.Index != (sender as DataGridView).CurrentCell.RowIndex && Convert.ToBoolean(row.Cells[e.ColumnIndex].Value) == true)
{
row.Cells[e.ColumnIndex].Value = false;
}
}
}
}
}
private void dataGridViewClient_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridViewClient.IsCurrentCellDirty)
{
dataGridViewClient.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
You can use CellEndEdit event of DGV, as it occurs after when the cell is modified. Kindly read the comments in below code snippet to use the code below:
private void dgrvUserProfileView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
int CheckedCount = 0;
//Make sure you have set True Value/ false Value property of check box column to 1/0 or true/false resp.
//Lets say your column 5th(namely Department) is a checked box column
if (dgrvUserProfileView.Columns[e.ColumnIndex].Name == "Department")
{
for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
{
if (Convert.ToBoolean(dgrvUserProfileView.Rows[i].Cells["Department"].Value) == true)
{
CheckedCount = CheckedCount + 1;
}
}
if (CheckedCount == 1)
{
for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
{
if (Convert.ToBoolean(dgrvUserProfileView.Rows[i].Cells["Department"].Value) == true)
{
dgrvUserProfileView.Rows[i].Cells["Department"].ReadOnly = true;
}
}
}
else
{
for (int i = 0; i <= dgrvUserProfileView.Rows.Count - 1; i++)
{
dgrvUserProfileView.Rows[i].Cells["Department"].ReadOnly = false;
}
}
}
}
Hope this helps!
private void dgvlist_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int currentcolumnclicked = e.ColumnIndex;
for (int i = 0; i <= dgvlist.Columns.Count - 1; i++)
{
if (dgvlist.Columns[i] is DataGridViewCheckBoxColumn)
{
if (Convert.ToString(dgvlist.CurrentRow.Cells[i].EditedFormattedValue) == "True" && i !=currentcolumnclicked)
{
dgvlist.CurrentRow.Cells[i].Value = false;
}
}
}
}
private void dgvCaixa_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if ((sender as DataGridView).CurrentCell is DataGridViewCheckBoxCell)
{
foreach (DataGridViewRow row in dgvCaixa.Rows)
{
if (row.Index != dgvCaixa.CurrentCell.RowIndex && Convert.ToBoolean(row.Cells[e.ColumnIndex].Value) == true)
{
row.Cells[e.ColumnIndex].Value = false;
}
}
}
}
in vb.net:
Private Sub DataGridViewJobsList_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridViewJobsList.CellValueChanged
If TypeOf TryCast(sender, DataGridView).CurrentCell Is DataGridViewCheckBoxCell Then
Dim cell1 As DataGridViewCell
cell1 = TryCast(sender, DataGridView).CurrentCell
If cell1.Value = True Then
For Each row As DataGridViewRow In TryCast(sender, DataGridView).Rows
If row.Index <> cell1.RowIndex AndAlso row.Cells(e.ColumnIndex).Value = "1" Then
row.Cells(e.ColumnIndex).Value = False
End If
Next
End If
End If
End Sub
Private Sub DataGridViewJobsList_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridViewJobsList.CurrentCellDirtyStateChanged
If Me.DataGridViewJobsList.IsCurrentCellDirty Then
DataGridViewJobsList.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
You can set the VirtualMode setting to TRUE on the DGV to allow only one checkbox. and you can set VirtualMode setting to FALSE on the DatagridView to check more than one.
I think this is the easiest way for the solution.
Without worrying about the Column and never fail, try this:
private void DgvIVA_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dg = (DataGridView)sender;
if (dg.Rows.Count == 0) return;
if (dg.Rows[e.RowIndex].Cells[e.ColumnIndex].GetType() == typeof(DataGridViewCheckBoxCell))
{
int rowSelIndex = e.RowIndex;
foreach (DataGridViewRow row in dg.Rows)
{
if (row.Index != rowSelIndex)
{
row.Cells[e.ColumnIndex].Value = false;
}
}
}
}
private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
try
{
string val = dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (val == "False")
val = "True";
else if (val == "True")
val = "False";
dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = val;
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
string active = "";
if (i != e.RowIndex)
{
if (val == "False")
{
dataGridView3.Rows[i].Cells[1].Value = "True";
active = "Y";
}
else if (val == "True")
{
dataGridView3.Rows[i].Cells[1].Value = "False";
active = "N";
}
}
else
{
if (val == "False")
active = "N";
else
active = "Y";
}
}
}
catch (Exception ex)
{ }
}
}
i am using checkbox in gridview..to get the checkbox id i am using the following code..
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows.Cells[1].Text;
idCollection.Add(strID);
}
}
}
BUT THE KEYWORD "CELLS"..do not support..i am getting an error.."System.Web.UI.WebControls.GridViewRowCollection' does not contain a definition for 'Cells' "
This is the way you have to check
foreach (GridViewRow grRow in grdACH.Rows)
{
CheckBox chkItem = (CheckBox)grRow.FindControl("checkRec");
if (chkItem.Checked)
{
strID = ((Label)grRow.FindControl("lblBankType")).Text.ToString();
}
}
That's correct; the GridViewRowCollection class does not contain either a method or a property with the name Cells. The reason that matters is that the Rows property of the GridView control returns a GridViewRowCollection object, and when you call GridView1.Rows.Cells, it is searching for a Cells property on the GridViewRowCollection object returned by the Row property.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)GridView1.Rows[i].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
idCollection.Add(strID);
}
}
}
foreach (GridViewRow rowitem in GridView1.Rows)
{
CheckBox chkDelete = (CheckBox)rowitem.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = rowitem.Cells[1].Text;
idCollection.Add(strID);
}
}
}
I will have a treenode with some nodes. I will have a datagridview on my form. Initially i will load some data in to the gridview. Now if i select a node at my trreview i would like to make a particular row as selected one.
Suppose my treeview is as follows
Root
|-> Child
|->Child1
If i select child i would like to make a corresponding row as selected if child1 another row should get selected.
Any idea please
1) you need to map the nodes to corresponding datagrid rows
this.dataGridView1.Rows[0].Tag = id; // a node id
2) handle node click event and find corresponding row by id and select it
if (tvwACH.SelectedNode.Parent != null)
{
int id = (int)tvwACH.SelectedNode.Tag ; // make sure you've already assigned tag when creating Three nodes and data rows
foreach(DataGridViewRow row in this.dataGridView1.Rows)
{
int rowId = (int)row.Tag ;
if(rowId == id)
{
row.Selected = ture;
}
else
{
row.Selected = false; //discard other rows
}
}
}
yourDataGridView.Rows(nRowIndex).Selected = true;
This is the code i have written
private void tvwACH_AfterSelect(object sender, TreeViewEventArgs e)
{
string node = string.Empty;
if (tvwACH.SelectedNode.Parent != null)
{
node = tvwACH.SelectedNode.Text.ToString();
if (node == "FileHeader")
{
int tag = Convert.ToInt16(tvwACH.SelectedNode.Tag.ToString());
this.dataGridView1.Rows[0].Tag = tag;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int rowId = (int)row.Tag;
if (rowId == tag)
{
row.Selected = true;
}
}
}
string strSwitch = tvwACH.SelectedNode.Parent.Text;
switch (strSwitch)
{
case "ACH":
{
dataGridView1.Visible = true;
dataGridView1.Rows.Clear();
node = tvwACH.SelectedNode.Text;
StreamReader sr = new StreamReader(node);
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
dataGridView1.Rows.Add(rectype[line.Substring(0, 1)].ToString(), line);
}
sr.Close();
}
break;
}
}
}
Try this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int flage = 1;
private void button1_Click(object sender, EventArgs e)
{
flage = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
DataGridViewRow currentRow = dataGridView1.SelectedRows[0];
TreeNode node1 = new TreeNode(currentRow.Cells[1].Value.ToString());
TreeNode node2 = new TreeNode(currentRow.Cells[2].Value.ToString());
TreeNode node3 = new TreeNode(currentRow.Cells[3].Value.ToString());
TreeNode[] TreeArray = new TreeNode[] { node1,node2, node3 };
TreeNode finalnode = new TreeNode(currentRow.Cells[0].Value.ToString(), TreeArray);
treeView1.Nodes.Add(finalnode);
flage = 1;
break;
}
else
{
flage = 0;
}
}
if(flage==0)
{
MessageBox.Show("Row is not Selected Please select the row");
}
}
private void button2_Click(object sender, EventArgs e)
{
treeView1.Nodes.Remove( treeView1.SelectedNode);
}
int flage2;
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
flage2 = 1;
break;
}
else
{
flage2 = 0;
}
}
if (flage2 == 0)
{
MessageBox.Show("Row is not selected Please select the row");
}
}
}