How to use checkbox check change without refreshing page in ASP.NET - asp.net

I have two checkboxes in a gridview. The scenario is this: only one of these checkboxes can be chosen or none of them.
My problem is that when my gridview got too big, every time I check or uncheck each row the page refresh that is because of I set auto post back = true! What should I do to avoid this refreshing and the scenario works except UpdatePanel!
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="morakhasi" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxMorakhasi" OnCheckedChanged="chkboxMorakhasi_CheckedChanged" runat="server" AutoPostBack="true"/>
</ItemTemplate>
<HeaderStyle Font-Size="16px" Width="80px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="taiid" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxTaiid" OnCheckedChanged="chkboxTaiid_CheckedChanged" runat="server" Checked="True" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
Code behind:
protected void chkboxTaiid_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb2.Checked = Convert.ToBoolean(0);
}
}
protected void chkboxMorakhasi_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb1.Checked = Convert.ToBoolean(0);
}
}

You should use UpdatePanel control to do this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:CheckBox
OnCheckedChanged="chkCompany_OnCheckedChanged"
AutoPostBack="True" CssClass="chkCompany"
ClientIDMode="Static" ID="chkCompany" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>

Well, first up, when you say the grid is large? Well, how large? 20 rows or 2000 rows?
When Google, or even Microsoft asks interview questions? A good number of these questions are of a how high, how far, how big type of questions. And the reason for that is simple:
They want to determine if you have a mind can is able to evaluate scope and scale of problems that you have to solve. (so, they might ask how would you move Mount Fuji?)
anyway:
I can't image the grid has what, 30 rows on a page? (why so many and why so large??).
I mean, if you have more, then we need to know how many more?
However, lets get the first problem solved. (the check box issue), and then we can try and deal with the re-plot/refresh issue.
Ok, so say we have this grid markup - grid + 2 check boxes
<asp:GridView ID="GVHotels" runat="server" class="table" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Choice 1" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server"
OnCheckedChanged="chk1_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Choice 2" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk2" runat="server"
OnCheckedChanged="chk2_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load the grid is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we have this:
And our two check box changed events are this:
protected void chk1_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk2")).Checked = false;
}
protected void chk2_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk1")).Checked = false;
}
Ok, so we are done.
the next issue is performance? A grid of say 20-40 rows on the form should work ok.
I think just drop a update panel around the grid, and you done.
So, we drop in script manager, and then this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
-- above grid goes here!!!
</ContentTemplate>
</asp:UpdatePanel>
Now, I just tested the above with 50 rows on the screen. I can't see or feel, or notice ANY replot delay, and in fact the check box reacts as fast as my mouse click. In fact the check box status changes quite much as fast as the mouse click, and in fact quite much at the same time I hear the click.
So, above is the layout for the code you require here. If there is some "slow" ness, or delay, or your data set is larger, then perhaps some kind of data pager should be introduced. On the other hand, you not shared, or noted how many rows this grid is displaying on the screen. And without that information, we shooting in the dark here as to what possible solutions(s) exist (or that what you have is a very bad idea).

Related

Unable to get selected item of dx:ASPxListBox on ASPxGridView_Updating event of devexpress control

I have used dx:ASPxGridView where I have one dx:GridViewDataTextColumn with EditItemTemplate which contain dx:ASPxListBox. When I click on update command I am not able to get selected items of dx:ASPxListBox under ASPxGridView_Updating.
<dx:ASPxGridView
ID="ASPxGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="TradersDS"
KeyFieldName="TraderId">
<SettingsEditing Mode="PopupEditForm" PopupEditFormWidth="600px" />
<ClientSideEvents RowDblClick="function(s, e)
{
s.StartEditRow(e.visibleIndex);
}"
EndCallback="PrepareGridViewForNewDesing" Init="PrepareGridViewForNewDesing" />
<Columns>
....
<dx:GridViewDataTextColumn FieldName="CounterParty" VisibleIndex="3">
<EditItemTemplate>
<dx:ASPxListBox ID="lstCounterParty" runat="server" SelectionMode="CheckColumn" EnableSelectAll="true"
Width="285"
Height="300"
DataSourceID="CounterPartiesDS"
ValueField="ID"
ValueType="System.String"
TextField="Name">
<%-- <ClientSideEvents SelectedIndexChanged="function(s, e) {lbModels.PerformCallback('1');}" />--%>
</dx:ASPxListBox>
</EditItemTemplate>
</dx:GridViewDataTextColumn>
...
</Columns>
</dx:ASPxGridView>
C# Code..
protected override void ASPxGridView_Updating(object sender, ASPxDataUpdatingEventArgs e)
{
var gridView = sender as ASPxGridView;
GridViewDataColumn list = gridView.Columns["CounterParty"] as GridViewDataColumn;
var counterPartyListBox = (ASPxListBox)gridView.FindEditRowCellTemplateControl(list, "lstCounterParty");
string selectedItemsAsString = string.Empty;
foreach (ListEditItem item in counterPartyListBox.SelectedItems)
selectedItemsAsString += item.Value + ";";
base.ASPxGridView_Updating(sender, e);
}
Here I always get count 0 of SelectedItems. On addition to this My devExpress control version are 9.3.3
What is wrong with this code any help , guidance really appreciated.
Make sure that you set the ASPxListBox.ValueType property to the corresponding .NET type that matches the type of the "ValueField" column.
May be, according to the (ValueField="ID"), the (ASPxListBox.ValueType) should be numeric? (System.Int32, etc.)

itemTemplate item id not existing in code behind

I am trying to create textboxes that are equal to the number of rows in grid view (databound from db). here is my markup
<asp:GridView ID="quizGrid" runat="server" CssClass="Grid" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="admissionNO" HeaderText="Admission NO"/>
<asp:BoundField DataField="studentName" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Textbox runat="server" ID="marks" > </asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
but when i use the marks in code behind it says
quizGrid_marks_0 does not exists in the current context
what im doing wrong here?
You can't access your textbox like that in code behind file, rather you need to find them in RowDataBound event like this:-
protected void quizGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox marks = (TextBox)e.Row.FindControl("marks");
txtMarks.Text = "Test";
}
}
Edit:
Okay, suppose you have a button btnGetData with button click event as btnGetData_Click, then you can find the textbox text by looping through the gridview rows like this:-
protected void btnGetData_Click(object sender, EventArgs e)
{
GridView quizGrid = (GridView)Page.FindControl("quizGrid");
foreach (GridViewRow row in quizGrid.Rows)
{
TextBox marks = (TextBox)row.FindControl("marks");
}
}

Asp.net concerned with gridview paging

I am trying to paging in asp.net.
so how to code for the paging.I want group of 5 items in bunch and next page carry same group of information.
In your grid view you can add these line which will set your page with a group of 5 items
<PagerSettings PageButtonCount="5"></PagerSettings>
Try this for pagination in Grid View.
protected void TeacherGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
myGrid.PageIndex = e.NewPageIndex;
bindDataToGrid();
}
// add columns per your requirement and bind the grid with data source.
<asp:gridview id="myGrid" runat="server" AutoGenerateColumns="False"
AllowPaging="True" PageSize="5" OnPageIndexChanging="myGrid_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
In your GridView you have to give the size that you want to show the number of results in the GridView also in code behind you have to set your page index so whenever you go to the next 5 records, it will show the next 5 records instead of same.
Fix the PageSize also use a OnPageIndexChanged to show the unique records every time.
<asp:GridView ID="myGridView" PageSize="5" OnPageIndexChanging="myGridView_OnPageIndexChanging" >
in codebehind you write this code in you OnPageIndexChanging...
protected void myGridView_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.myGridView.PageIndex = e.NewPageIndex;
this.myGridView.DataSource = this.Session["myData"];
this.myGridView.DataBind();
}

Radio list with SelectedIndexChanged not firing inside radgrid

I have a user control that contains a radio list that on SelectIndexChanged it updates a drop down.
I put together a basic page and add the user control to the page it works fine but when I move the control to inside a radgrid it doesn't work, it will post back but never call the SelectIndexChanged event.
I've pulled up 2 previous questions on this Q. 1 and Q. 2 which say that OnSelectedIndexChanged needed to be set in the aspx page. My issue is that the control doesn't exist in the aspx page and is created later so that solution does not work for me.
Working code
working.aspx
<TT:ToolTipControl ID="ToolTipEdit" runat="server" />
working.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ToolTipEdit.getEditToolTip("POL_TERM_CD", "DataPolTermDropDownlistEdit");
}
User Control
userControl.ascx.cs
public void getEditToolTip(string fieldName, string ddlName)
{
DataPolTermRadioListBox ccPolTermRadioListBox = new DataPolTermRadioListBox(); //custom radio list
ccPolTermRadioListBox.ID = "PolTermRadioListBox";
ccPolTermRadioListBox.AutoPostBack = true;
ccPolTermRadioListBox.SelectedIndexChanged += new System.EventHandler(updateParent);
ToolTip.Controls.Add(ccPolTermRadioListBox);
}
Broken Code
brokenPage.aspx
<telerik:RadGrid ID="rgState" Skin="WebBlue" runat="server" OnNeedDataSource="rgState_NeedDataSource"
AutoGenerateColumns="False" OnPreRender="rgState_PreRender">
<MasterTableView DataKeyNames="wrtnStPolId" AllowAutomaticUpdates="false" AllowAutomaticDeletes="true"
AllowAutomaticInserts="false" CommandItemDisplay="Top" AllowMultiColumnSorting="True"
EditMode="InPlace" GroupLoadMode="Server" Caption="State(s) and Exposure(s)">
<Columns>
<telerik:GridTemplateColumn AllowFiltering="false" HeaderText="Pol Type Nstd" SortExpression="nonStdPolTypeCd"
UniqueName="nonStdPolTypeCd">
<ItemTemplate>
<asp:Label ID="lblNonStdPolTypeCd" runat="server" align="center" Text='<%#DataBinder.Eval(Container.DataItem, "nonStdPolTypeCd")%>' />
</ItemTemplate>
<EditItemTemplate>
<cc1:DataNonStdTypeCdDropDownList ID="ddlNonStdTypeCd" runat="server" ClientIDMode="Predictable">
</cc1:DataNonStdTypeCdDropDownList>
<TT:ToolTipControl ID="ttcNonStdPolTypeCdEdit" runat="server" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
brokenPage.aspx.cs
protected void rgState_PreRender(object sender, EventArgs e)
{
RadGrid rgExpMod = (RadGrid)sender;
foreach (GridDataItem row in rgExpMod.Items)
{
GridDataItem gdiItem = (GridDataItem)row;
if (row.FindControl("ttcNonStdPolTypeCdEdit") != null)
{
DropDownList ddl = (DropDownList)row.FindControl("ddlNonStdTypeCd");
ddl.ID += row.RowIndex;
ddl.SelectedIndex = 2;
NCCI.PDC.Web.Controls.ucToolTip ttcNonStdPolTypeCdEdit = (NCCI.PDC.Web.Controls.ucToolTip)row.FindControl("ttcNonStdPolTypeCdEdit");
ttcNonStdPolTypeCdEdit.getEditToolTip("non_std_pol_type_cd", ddl.ID);
}
}
}

Unable to access the checkbox for Serverside coding

Below is my gridview ,
<asp:GridView ID="gridview1" AutoGenerateColumns="False" runat="server"
EnableModelValidation="True" >
<Columns>
<asp:CommandField ButtonType="Link" HeaderText="Delete" InsertImageUrl="~/_layouts/images/TBS.WebParts/Button-Delete-icon.png" ShowDeleteButton="true"/>
<asp:BoundField HeaderText ="Size" DataField="FileSize" />
<asp:BoundField HeaderText ="File" DataField="Size" />
<asp:TemplateField HeaderText="SupportIncluded">
<ItemTemplate>
<asp:CheckBox ID="Checkbox1" runat="server" Checked="false" />
</ItemTemplate>
Now on server side i want to check if the checkbox is checked or not on Submit button click event.
private void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValidPost())
{
bool flag = false;
for( int i=0; i < gridview1.Rows.Count ; i++)
{
if(dgdUpload.Rows[i].FindControl("Checkbox1"),CheckBox).Checked) erorr here...I also tried ....if(Checkbox1.checked)...but unable to access Checkbox1..it says it does not exist in the current context....
flag = true;
}
if(flag)
{
}
}
}
You need to access not only the row but also the template field control. Another option is to develop your own recursive version of FindControl that does a search on the whole tree and not just on one level.
Something like:
dgdUpload.Rows[i].Controls[5].FindControl("Checkbox1")
if I counted the columns in your gridview correctly 5 should be the index of the template field.

Resources