C# GridView Dynamic CheckBox Disappearing - c#

I have a fairly simple application which returns a list of failed reports with an ID, Name and Time Bound fields and Checkbox template field on the left.
I have a 'Reschedule' button which when pressed, should pick up the rows where the checkbox has been ticked and process them.
The GridView loads up successfully and I can select/unselect the CheckBoxes but when I press the 'Reschedule' button and return to the code, the checkboxes no longer exist.
I know this is related to Dynamic Controls/Postback and that the Checkboxes need to be re-created and I've tried numerous suggestions to previous similar questions but nothing has worked
GridView - AutoGenerate Columns False (tried true)
Button - OnClientClick="" (tried return false)
The fields are initially created and bound to a data table (the data table has 3 columns mapping to the 3 Bound fields) like this:-
TemplateField tfield = new TemplateField();
failedSchedulesGridView.Columns.Add(tfield);
BoundField bfield1 = new BoundField();
bfield1.HeaderText = "SI_ID";
bfield1.DataField = "si_id";
failedSchedulesGridView.Columns.Add(bfield1);
BoundField bfield2 = new BoundField();
bfield2.HeaderText = "SI_NAME";
bfield2.DataField = "si_name";
failedSchedulesGridView.Columns.Add(bfield2);
BoundField bfield3 = new BoundField();
bfield3.HeaderText = "SI_UPDATE_TS";
bfield3.DataField = "si_update_ts";
failedSchedulesGridView.Columns.Add(bfield3);
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
Page_Load
As can be seen I've tried recreating the GridView columns here but it didn't work and is commented out
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//TemplateField tfield = new TemplateField();
//failedSchedulesGridView.Columns.Add(tfield);
//BoundField bfield1 = new BoundField();
//bfield1.HeaderText = "SI_ID";
//bfield1.DataField = "si_id";
//failedSchedulesGridView.Columns.Add(bfield1);
//BoundField bfield2 = new BoundField();
//bfield2.HeaderText = "SI_NAME";
//bfield2.DataField = "si_name";
//failedSchedulesGridView.Columns.Add(bfield2);
//BoundField bfield3 = new BoundField();
//bfield3.HeaderText = "SI_UPDATE_TS";
//bfield3.DataField = "si_update_ts";
//failedSchedulesGridView.Columns.Add(bfield3);
}
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
}
OnRowDataBound
protected void OnRowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
cbx++;
CheckBox cb = new CheckBox();
cb.ID = "cb" + cbx;
e.Row.Cells[0].Controls.Add(cb);
}
}
The Code fails when I try to access the Checkboxes after the 'Reschedule' button is pressed because the checbox is not found :-
protected void ReschedulePB2_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in failedSchedulesGridView.Rows)
{
i++;
string cbName = "cb" + i;
CheckBox cb = (CheckBox)row.Cells[0].FindControl(cbName);
if (cb.Checked)

try this
Write this in your aspx page
<asp:GridView ID="failedSchedulesGridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" Width="850px" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField >
<HeaderTemplate>
<asp:CheckBox ID="cbHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="si_id" HeaderText="SI_ID" SortExpression="si_id" />
<asp:BoundField DataField="si_name" HeaderText="SI_NAME" SortExpression="si_name" />
<asp:BoundField DataField="si_update_ts" HeaderText="SI_UPDATE_TS" SortExpression="si_update_ts" />
</Columns>
</asp:GridView>
your page load should look like this
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
failedSchedulesGridView.DataSource = dt;
failedSchedulesGridView.DataBind();
}
}
your reschedule click would be
protected void ReschedulePB2_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in failedSchedulesGridView.Rows)
{
CheckBox cb = (CheckBox)row.Cells[0].FindControl("cbItem");
if (cb.Checked)

Related

how to get dynamic check box status an asp in a gridview in asp webform?

i have a gridview in a asp.net webform and i add it a check box column like this (the dataTable first column(0) is empty in sql data source and i add check boxes on the column cells):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (rowNum != 0)//except first row
{
CheckBox cb = new CheckBox();
cb.Enabled = true;
e.Row.Cells[0].Controls.Add(cb);//row[0]=first clmn-and this event happend for all rows
}
rowNum++;
}
now i have a dynamic check box column! and user should check some of them and click the submit then i need the row number of the checked check boxes.
how can i do this?
i tried this before:
DataTable editTable = new DataTable();
editTable.Rows.Add(GridView1.Rows[0]);
var x = editTable.Rows[0][0];
but the x cannot get the check box true or false! it seems that getting me the original field under the check box content.
regards.
Instead of creating the controls dynamically which in most cases results in a lot of trouble, you could add the CheckBoxes in one or more template columns. The following sample shows how to add a checkbox in a template column and how to retrieve the value afterwards:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chb" runat="server" />
<asp:HiddenField ID="hiddenId" runat="server"
Value='<%# DataBinder.Eval(Container.DataItem, "Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Text" />
</Columns>
</asp:GridView>
In my sample, I've bound some data to the GridView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var dt = GetData();
gridView.DataSource = dt;
gridView.DataBind();
}
}
private DataTable GetData()
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Text", typeof(string));
for (int i = 0; i < 10; i++)
dt.Rows.Add(new object[] { i, "Test text " + i.ToString() });
return dt;
}
If you need to set the value, you can do so in the RowDatabound event. The following code shows how to retrieve the value of the Checkbox controls:
protected void btn_Click(object sender, EventArgs e)
{
List<int> checkedIds = new List<int>();
foreach(GridViewRow row in gridView.Rows.OfType<GridViewRow>()
.Where(x => x.RowType == DataControlRowType.DataRow))
{
var hiddenId = (HiddenField)row.Cells[0].FindControl("hiddenId");
var checkBox = (CheckBox) row.Cells[0].FindControl("chb");
if (checkBox.Checked)
checkedIds.Add(int.Parse(hiddenId.Value));
}
}

Access gridview rows after postback

Good day!
I need to dynamycally upload files and display information in gridview.
After file upload, i need to select file type in dropdown.
But after postback i can't access Gridview1 rows, and get selected file types. After postback Gridview1.Rows.Count = 0.
Is it possible to get selected values from DropDownLists?
<asp:GridView ID="GridView1" runat="server" ShowHeader="False" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FileName" />
<asp:TemplateField HeaderText="FileType">
<ItemTemplate>
<asp:DropDownList runat="server">
<asp:ListItem Value="Val1">Val1</asp:ListItem>
<asp:ListItem Value="Val2">Val2</asp:ListItem>
<asp:ListItem Value="Val3">Val3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField DeleteText="Remove" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:FileUpload ID="FileUpload" runat="server" onchange="this.form.submit()" />
Thanks
In Page_Load, during PostBack, GridView rows is empty.
protected void Page_Load(object sender, EventArgs e)
{
RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
}
private void AddRow(string file)
{
DataTable dt = (DataTable)Page.Session["Files"];
if (dt == null)
{
AddDataTableToSession();
dt = (DataTable)Page.Session["Files"];
}
DataRow dr = dt.NewRow();
dr["FileName"] = file;
dr["FileType"] = 0;
dt.Rows.Add(dr);
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
private void AddDataTableToSession()
{
DataTable dt = new DataTable("Files");
DataColumn dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileType", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["Files"] = dt;
}
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
int recordToDelete = e.RowIndex;
DataTable dt = (DataTable)Page.Session["Files"];
int cn = dt.Rows.Count;
dt.Rows.RemoveAt(recordToDelete);
dt.AcceptChanges();
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
Try by changing Ispostback like this.
if (!IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
(or)
if (IsPostBack == false && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
So that, if page load occurs, Your if condition will get true.
You can find the drop down list and update it with the value in the RowDataBOund event of gridview as follows
protected void Page_Load(object sender, EventArgs e)
{
//RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
else
{
AddDataTableToSession();
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
FilesGridView.RowDataBound += KBFilesGridView_RowDataBound;
}
and row databound will be as follows
void KBFilesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
DataRow dr= ((DataRowView)e.Row.DataItem).Row;
ddl.SelectedValue = dr["FileType"].ToString();
}
}
Similary you can get the value of dropdown for remove method as well as follows
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
if(ddl.SelectedValue == "someValue") doSomeThing();
}
}
}

dropdownlist disable in asp.net

when admin approve/reject any document once then when admin again login then he/she not be able to approve/reject documents again and dropdownlist will be disabled only for those documents which can be once approve/reject then when admin view any new documents then drop down will be enable and when admin approve/reject this document then it will be disable dropdownlist for not approve /reject again
for this i do this
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList abc = (e.Row.FindControl("DropDownList9") as DropDownList);
abc.Enabled = false;
}
}
but this code show me all dropdownlist are disable .
any solution how i will do this?
According to your comment, I assume your DataSource is either DataTable or DataSet.
If so, you want to cast DataItem to DataRowView inside RowDataBound Event to get the value of the status column.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList runat="server" ID="DropDownList9">
<asp:ListItem Text="Approve" Value="1" />
<asp:ListItem Text="Reject" Value="2" />
<asp:ListItem Text="Pending" selected="selected" Value="3">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var table = new DataTable();
table.Columns.Add("Id", typeof (int));
table.Columns.Add("Name", typeof (string));
table.Columns.Add("ApproveID", typeof(string));
table.Rows.Add(1, "Jon Doe", "1");
table.Rows.Add(2, "Eric Newton", "2");
table.Rows.Add(3, "Marry Doe", "3");
GridView1.DataSource = table;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as DataRowView;
var dropDownList = e.Row.FindControl("DropDownList9") as DropDownList;
// Get value from ApproveID column,
// and check whehter Approve, Reject or others.
switch (item["ApproveID"].ToString())
{
case "1":
case "2":
dropDownList.Enabled = false;
break;
default:
dropDownList.Enabled = true;
break;
}
}
}
You need to access the data item from each row, I am assuming it is available on the object your are binding to the grid, and determine if they have been approved / rejected. If so then you should run you logic to disable:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var yo = (YOUR-OBJECT)e.Row.DataItem;
if(yo.Status !== null OR yo.Status != 'Not Reviewed'){
//Find the DropDownList in the Row
DropDownList abc = (e.Row.FindControl("DropDownList9")
as DropDownList);
abc.Enabled = false;
}
}
}
you can ask on which row you are with this code:
if (e.Row.RowIndex == <aRowNumber>)
{
...
}

checkedbox found uncheck on previous page after clicking on next page

when i checked [checked box] data on my page (1) and then go on to next page (2) through paging(bottom button of pages like [1234]) and then checked data on page (2).
when i came back to page (1) then it remain unchecked as i don't checked anything!!!
all the things remains at its original positions. all are unchecked on both pages .
when coming from 1 page to page 2 (check-boxes of page 1 forget his value and get unchecked) and after when coming from page 2 to page 1 same thing happens.
sorry for my bad and rough English.
any suggestion??
If its a gridview or any repeater control try this
Gridview HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True"
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Codes
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridView1.PageIndex = e.NewPageIndex;
BindData();
RePopulateValues();
}
And
private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int) GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;
// Check in the Session
if (Session[CHECKED_ITEMS] != null)
categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session[CHECKED_ITEMS] = categoryIDList;
}
And
private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
myCheckBox.Checked = true;
}
}
}
}
Bind Data Code
EDIT
/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";
private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(QUERY_SELECT_ALL_CATEGORIES,
myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}
For more details chk this Maintaining_State_of_CheckBoxes
When you are navigating from one page to another ,your page refreshes so it cant retain value for checkbox,If you want to do this you have to do it from code behind ,write code
Checkbox.Checked=True in !IsPostback according to your valid conditions.

how to delete a row from the gridview by using a button outside the gridview

This seems like a repeated question but i'm not able to get my answer.
I have a grid view and I need to delete a particular row, when I click on a button outside the gridview.
protected void btnDelete_Click(object sender, EventArgs e)
{
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[DataGV1.SelectedIndex];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
The session variable has the previous state of datatable.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
_selectedIndex = int.Parse(e.CommandArgument.ToString());
}
Gridview controls
onselectedindexchanged="DataGV1_SelectedIndexChanged"
OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
<Columns>
<asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
<asp:BoundField DataField="role" HeaderText="role" HeaderText="Frist_name"
SortExpression="first_name" Text="First_name" />
</Columns>
</asp:GridView>
This doesn't seem to work.
Can u please tell me where I am going wrong?
If button is outside the GridView then no need to handle RowCommand event (In fact it is inappropriate).
Suggestion:
You have to add a TemplateField column, drop the CheckBox control in ItemTemplate of TemplateField and write code in click handler of button to traverse the GridView.Rows collection, identify the selected row by reading value of CheckBox control and perform deletion action if that CheckBox is checked.
Demo DataSource (List<T>)
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Item> Data()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
return list;
}
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />
Code-behind (Page_Load)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = Item.Data();
GridView1.DataSource = Session["data"];
GridView1.DataBind();
}
/*--- RowCommand handler ---*/
GridView1.RowCommand += (sa, ea) =>
{
ViewState["RowIndex"] = ea.CommandArgument.ToString();
};
/*--- Delete button click handler ---*/
btnDelete.Click += (sa, ea) =>
{
if (ViewState["RowIndex"] != null)
{
int index = int.Parse(ViewState["RowIndex"].ToString());
List<Item> items = Session["data"] as List<Item>;
items.RemoveAt(index);
GridView1.DataSource = Session["data"];
GridView1.DataBind();
ViewState["RowIndex"] = null;
}
};
}
You have to store the _selectedIndex in a ViewState, and then on delete button click you retrieve the _selectedIndex from the Viewstate and use that to delete the row from your dataset, and reload the grid.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
ViewState["SelIndex"] = e.CommandArgument.ToString();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if(ViewState["SelIndex"] == null)
return;
int selIndex = int.Parse(ViewState["SelIndex"]);
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[selIndex ];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
take a look at these articles that would explain to delete a single/multiple rows from gridview.
http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/
http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/

Categories