Checked checkbox in gridview, in c# codebehind checked property is false - c#

I have custom upload control. The control has gridview with the uploaded documents and the first column has checkbox for selecting documents I want to delete by clicking Delete button. The upload control is contained in other UserControls almost everywhere in the application and works properly, except at one control. The problem is when I check some document for deleting, when the code executes the checked property of the checkbox is false.
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false" ShowHeader="true"
CssClass="DataGrid" Width="100%" OnRowDataBound="gvFiles_RowDataBound">
<HeaderStyle HorizontalAlign="left" CssClass="UploadControlGridHeader" />
<RowStyle CssClass="dlcell" />
<EditRowStyle CssClass="dlsell" />
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemStyle Width="8%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkFile" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this is the delete button event
protected void btnDelete_Click(object sender, EventArgs e)
{
for (int i = 0; i < gvFiles.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvFiles.Rows[i].Cells[0].FindControl("chkFile");
if (chk.Checked)
{
// If file is marked/checked to be deleted
// then delete it.
DeleteFile(i);
}
}
Session[KEY_VIEWSTATEFILES] = this.FileList;
// Repopulate gridview
BindToGridView();
// Call command to keep same visible screen.
CustomCommandEventArgs command = new CustomCommandEventArgs(COMMAND_FILE_DELETED, null);
OnHappyCommand(command);
}

Not having your DeleteFile(i) code, I can't be sure, but I will take a guess that into that function you remove/delete the row. Am I right? If yes, then it change the index of all your rows, which make you think it is not checked when you check the row that you remember to have checked. You will have to use a backward for loop to fix this.

Related

Asp.net/c# -> Gridview Pager doesn't get updated when gridview rows are filtered (or hidden)

I have the below code where I have some conditions because of which I have to hide the row from showing to end user. "ShowRow" is a boolean value that gets set in GetUnitOfMeasure function (not copied here) based on these conditions.
There are some real conditions which is forcing me to hide. I tried to include them while building data source but I have to hide it before display.
Problem I am facing is the paging is not getting refreshed based on total rows shown at the end. For example, if I have TOTAL of 200Rows in the grid and only 2 rows needs to be shown and if these 2 rows are found in paging 3, then when page is loaded it still shows paging 1 2 3 4 and 3rd page has the valid 2 rows.
Please suggest.I have also used "onDataBound" against gridview (not copied here) but I just hide some columns here.
ASPX page
<asp:GridView ID="SearchResults" runat="Server" AutoGenerateColumns="false" EnableViewState="false"
AllowPaging="true" PageSize="50" OnDataBound ="SearchResults_DataBound" OnRowDataBound="SearchResults_RowDataBound">
<RowStyle CssClass="EvenRow" />
<AlternatingRowStyle CssClass="OddRow" />
<Columns>
<asp:TemplateField meta:resourceKey="UmSellField">
<ItemStyle CssClass="alpha" />
<HeaderStyle CssClass="alpha" />
<ItemTemplate>
<asp:Label ID="UmSellLabel" runat="server" EnableViewState="false" Text='<%# GetUnitOfMeasure(Container.DataItem,false) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
codebehind
protected void SearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
e.Row.Visible = showRow;
e.Row.Cells[0].Visible = showRow;
}
}

Adding cells in GridView

How can i add cell in specific column for each row in gridview,i want to use RowCreated Events.
i have gridview that has 3 columns (ProductName, Price, Count) i get (ProductName, Price) from database, and i want to add value for (count), ex: (Kitkat, 2$ ) i want to add number 5 to (count) column, i want to handle this operation when each row created.
Thanks
Since you haven't shown your markup, I'm going to assume (based on your comment) that the first two columns are <BoundFields>. If that's the case, I would add a third column as a <TemplateField>, place a Label in it, and use the RowDataBound event to add the correct number to the Label.
Here is what the markup would look like:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:TemplateField HeaderText="Count">
<ItemTemplate>
<asp:Label ID="countLbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label countLbl = (Label)e.Row.FindControl("countLbl");
//Your logic for what number to use should go here, I'm just defaulting to 5.
countLbl.Text = "5";
}

Form Re-Submission Deletes Next GridView Row

I have a Gridview and the OnRowDeleting method with removes a record from the database and the gridview.
My problem is that when a user click the delete button in the Gridview the record will be removed from the database but the GridView does not show this update (does not refresh). If the user then refreshes the page causing a form re-submission then the GridView deletes the row below the originally deleted row and so on if the page is refreshed again.
How can I prevent this from happening?
Here is my gridview:
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" >
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:ButtonField CommandName="select" ButtonType="Link" Text="hello" />
<asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
</asp:CommandField>
</Columns>
</asp:GridView>
Here is the OnRowDeleting method.
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID); // Deletes Questionniare from database
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
}
You could always redirect the user to the initial page after the row was deleted, e.g. in the RowDeleted handler.
Response.Redirect(Request.RawUrl);
This should work because the delete action is a POST command to the current .aspx page.

asp.net trigger for a checkbox control

Hi All i am using the below code and wanted to make a button visible and invisible based on checkbox status. I am using the trigger to call a event where i will write code to make that button visible or invisible. If i use the below code i get an error like "System.InvalidOperationException: A control with ID 'chkDelete' could not be found for the trigger in UpdatePanel 'UpdatePanel1'." Please help me.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers ="false">
<ContentTemplate>
<asp:GridView ID="gvEventMechanic" runat="server" AutoGenerateColumns="False" PageSize="5"
GridLines="None" AllowSorting="true" BorderWidth="1"
EnableViewState="true" AllowPaging="true">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Disable
</HeaderTemplate>
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" AutoPostBack="true" ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="chkDelete" EventName="CheckBoxEventChanged" />
</Triggers>
</asp:UpdatePanel>
As an alternative, why don't you use client-side environment to do this? It's more easy and more native.
$('#input[type=checkbox][id*=chkDelete]').change(function(){
$('#button').toggleClass('disabled');
});
Now, based on this class, you can use CSS to dim your button, if it's a span, or a div (custom button). Otherwise you can use:
$('#input[type=checkbox][id*=chkDelete]').change(function(){
if ($(this).is(':checked'))
{
$('#button').removeAttr('disabled');
}
else
{
$('#button').attr('disabled', 'disabled');
}
});
This will let you get all the information you need to delete the appropriate record.
// If you bind a list of objects as your data source you can use this to get the
// index into the list.
protected void OnCheckedChanged( Object sender, EventArgs e )
{
if ( sender is CheckBox )
{
// we do this to get the index into the list of the item we want to work with.
CheckBox cb = sender as CheckBox;
GridViewRow gvr = cb.NamingContainer as GridViewRow;
int dataItemIndex = gvr.DataItemIndex; // index into your list, regardless of page
int rowIndex = gvr.RowIndex; // row index in gridview.
}
}
ControlId for the CheckBox field <asp:CheckBox ID="chkDelete" runat="server" AutoPostBack="true" ></asp:CheckBox> will different for each row that is why it can't map the controlId to the trigger.
I suggest you to use checkbox's CheckedChanged event to trigger your method.
Yes it is CheckedChanged.
Although it doesnot look what you have mentioned in checkbox. but it works this way.

Selecting Multiple Check Boxes Inside a Grid View Control by clicking the Column Label Header

I have a grid view control with Template Field containing Item Template as Checkbox control
and the Header Template is containing the label with column header name.
I want to click the coulmn header label and all the check boxes must be checked once.
Please provide me some examples or ideas how i can achieve this
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="" >
<ItemTemplate>
<asp:CheckBox ID="val_id" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<label>
Rise Needed
</label>
</HeaderTemplate>
</asp:TemplateField>
<Columns>
Change your HeaderTemplate label to be a LinkButton and assign the Click event.
<HeaderTemplate>
<asp:LinkButton ID="btnRiseNeeded" runat="server" Text="Rise Needed" OnClick="btnRiseNeeded_Click" />
</HeaderTemplate>
Then when the button is clicked loop through you GridView rows and check the box.
foreach(var row in GridView2.Rows)
{
var cbx = (CheckBox)row.FindControl("val_id");
cbx.Checked = true;
}
This code is off the top of my head so might need some modifying. Also, I'm not sure if the checkboxes will stay checked on PostBack. Give it a try.

Categories