I have created a paginated grid view which contains check boxes for multiple selection.But while looping through the data-row in the grid-view only last pages row values only I am able to get.I know it's because of the pagination.
My code is below
protected void btnSaveItemMapping_Click(object sender, EventArgs e)
{
grdCustomers.AllowPaging = false;
foreach (GridViewRow gvrow in grdCustomers.Rows)
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkBoxBrandCustomers");
if (myCheckBox.Checked == true)
{
Label lblCustomerCode = (Label)gvrow.FindControl("lblCustomerCode");
//INSERT TO DATABSE
}
}
grdCustomers.AllowPaging = true
}
Keeping check box checked after changing page index like below code.
protected void grdCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
savechkdvls_cst();
grdCustomers.PageIndex = e.NewPageIndex;
if (Session["AllCustomers"] != null)
{
lstAllCustomers = (List<CustomerMaster>)Session["AllCustomers"];
}
grdCustomers.DataSource = lstAllCustomers;
grdCustomers.DataBind();
chkdvaluesp_cst();
}
private void chkdvaluesp_cst()
{
ArrayList usercontent = (ArrayList)Session["chkditems_customers"];
if (usercontent != null && usercontent.Count > 0)
{
foreach (GridViewRow gvrow in grdCustomers.Rows)
{
int index = Convert.ToInt32(grdCustomers.DataKeys[gvrow.RowIndex].Value);
if (usercontent.Contains(index))
{
CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkBoxBrandCustomers");
myCheckBox.Checked = true;
}
}
}
}
private void savechkdvls_cst()
{
ArrayList usercontent = new ArrayList();
int index = -1;
foreach (GridViewRow gvrow in grdCustomers.Rows)
{
index = Convert.ToInt32(grdCustomers.DataKeys[gvrow.RowIndex].Value);
bool result = ((CheckBox)gvrow.FindControl("chkBoxBrandCustomers")).Checked;
// Check in the Session
if (Session["chkditems_customers"] != null)
usercontent = (ArrayList)Session["chkditems_customers"];
if (result)
{
if (!usercontent.Contains(index))
usercontent.Add(index);
}
else
usercontent.Remove(index);
}
if (usercontent != null && usercontent.Count > 0)
Session["chkditems_customers"] = usercontent;
}
Any help will be appreciated.
Related
I have the following code to load data from a list in sharepoint website to a custom web part.
private void Data_load()
{
DataTable dt = new DataTable();
string currentName = SPContext.Current.Web.CurrentUser.Name;
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Editor'/><Value Type='Person or Group'>" + currentName + "</Value></Eq></Where>";
using (SPSite site = new SPSite("http://spdev-6/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList lists = web.GetList("Lists/Advertisements");
SPListItemCollection items = lists.GetItems(query);
if (items.Count > 0)
{
//foreach(SPListItem item in items)
//{
// string decodeDescrip = Server.HtmlDecode( item["Details"].ToString());
// item["Details"] = decodeDescrip;
//}
dt = items.GetDataTable();
}
else
lbldata.Text = "No data to show";
GridViewD.DataSource = dt;
GridViewD.DataBind();
HttpContext.Current.Session["Advertisement"] = dt;
}
}
}
Now the issue is i am getting Htmlencode data in one of the columns. Now i have to remove it from grid view. So how it can be removed ?
You can modify the Column in the DataTable before assigning it to the Grid. Look here and here.
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < row.Cells.Count - 1; i++)
{
if (row.Cells[i].Text == "0")
{
row.Cells[i].Text = "";
}
}
}
}
You could also change the value on DataBinding as described in this SO Answer.
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < row.Cells.Count - 1; i++)
{
if (row.Cells[i].Text == "0")
{
row.Cells[i].Text = "";
}
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//int test = Convert.ToInt32(ListBox1.SelectedValue.ToString());
//GetById(test);
foreach (ListItem listitem in ListBox1.Items)
{
if (listitem.Selected == true)
{
string email = listitem.Text;
GetByEmail(email);
}
}
}
This method should get selected item.I don't why but it show me that property selected is false for all items.
protected void Page_Load(object sender, EventArgs e)
{
ListBox1.Items.Clear();
SelectAllUsers();
}
public void SelectAllUsers()
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolService.User[] userArray = client.SelectAll(0);
int i = 0;
while (i < userArray.Length)
{
ListItem listItem = new ListItem();
listItem.Text = userArray[i].Email;
listItem.Value = userArray[i].Id.ToString();
ListBox1.Items.Add(listItem);
i++;
}
}
public void GetByEmail(string email)
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolClient.SchoolService.User user = client.GetUserByEmail(email);
if ((user.FirstName != null) || (user.LastName != null) || (user.Address != null) ||
(user.City != null) || (user.Email != null) || (user.Password != null))
{
txtId.Text = user.Id.ToString();
txtFirstName.Text = user.FirstName.ToString();
txtLastName.Text = user.LastName.ToString();
txtAddress.Text = user.Address.ToString();
txtCity.Text = user.City.ToString();
txtDateOfBirth.Text = user.DateOfBirth.ToShortDateString();
txtEmail.Text = user.Email.ToString();
txtPassword.Text = user.Password.ToString();
txtIsAdmin.Text = user.isAdmin.ToString();
}
else
{
MsgBox("None user was found", this.Page, this);
}
}
public void SelectAllUsers()
{
SchoolService.SchoolServiceClient client = new SchoolService.SchoolServiceClient();
SchoolService.User[] userArray = client.SelectAll(0);
int i = 0;
while (i < userArray.Length)
{
//if (userArray[i] != null)
//{
ListItem listItem = new ListItem();
listItem.Text = userArray[i].Email;
listItem.Value = userArray[i].Id.ToString();
ListBox1.Items.Add(listItem);
//}
i++;
}
}
Also sent methods which fill listBox with items (SelectAllUsers), and method which should take selected item from database (GetByEmail)
It doesn't find anything selected because on Page_Load you are rebinding the data again every time. You need to check if IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListBox1.Items.Clear();
SelectAllUsers();
}
}
I have two gridviews: parent and child. My goal is to update parent table with values from child table (this will be done in database). To complete this I need to read values from child gridview. I created below code but child rows are not read properly (I am gettin index is out of range error):
protected void btnUpdateSelected_Click(object sender, EventArgs e)
{
try
{
foreach (GridViewRow row_master in gvParent.Rows)
{
if (row_master.RowType == DataControlRowType.DataRow)
{
GridView gvChild = (GridView)gvParent.Rows[row_master.RowIndex].FindControl("gvChild");
if (gvChild != null)
{
foreach (GridViewRow row_child in gvChild.Rows)
{
if (row_child.RowType == DataControlRowType.DataRow)
{
CheckBox chckboxChild = (CheckBox)row_child.FindControl("chckboxChild");
if (chckboxChild.Checked == true & gvChild.Rows.Count == 1)
{
int index_master = Convert.ToInt32(row_master.RowIndex.ToString());
int index_child = Convert.ToInt32(row_child.RowIndex.ToString());
int rowID_a = Convert.ToInt32(gvParent.DataKeys[index_master].Values["ID"]);
int rowID_b = Convert.ToInt32(gvChild.DataKeys[index_master].Values["ID"]);
int serverID = Convert.ToInt32(gvParent.DataKeys[index_master].Values["ServerID"]);
int id = Convert.ToInt32(gvChild.DataKeys[index_child].Values["DeviceID"]);
int activeStatusID = Convert.ToInt32(gvChild.DataKeys[index_child].Values["ActiveStatusID"]);
string managedBy = gvChild.DataKeys[index_child].Values["ManagedBy"].ToString();
string monitoredBy = gvChild.DataKeys[index_child].Values["MonitoredBy"].ToString();
int managementProtocolID = Convert.ToInt32(gvChild.DataKeys[index_child].Values["ManagementProtocolID"]);
}
}
}
}
}
}
}
catch (Exception ex)
{
}
}
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.
here is the code for my viewstate. but it's only store one value.what i need is it will keep the selected multiple values in the checkbox. this method is to keep/hold the value of check box in gridview of paging situation.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ViewState["id"] = ID;
}
Try Following
Following Code may help u.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ArrayList SelecterdRowIndices=new ArrayList();
if(ViewState["SelectedRowIndices"]!=null)
{
SelecterdRowIndices=(ArrayList)ViewState["SelectedRowIndices"];
bool flag=false;
foreach (int i in SelecterdRowIndices)
{
if(i==Convert.ToInt32(ID))
{
flag=true;
break;
}
}
if(!flag)
{
SelecterdRowIndices.Add(ID);
}
}
else
{
SelecterdRowIndices.Add(ID);
}
ViewState["SelectedRowIndices"] = SelecterdRowIndices;
}