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.
Related
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.)
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).
I have the following datagrid view that is data bound with some data at the DB
I need to load the information in the data grid and make all the textbox in some columns(in the example only comes on but there are many) to be readonly or disable.
<asp:DataGrid ID="grdRequestTypeItem" TabIndex="1" runat="server" CssClass="Grid" AutoGenerateColumns="False"
AllowSorting="True" Visible="true">
<SelectedItemStyle CssClass="GridSelectedItem"></SelectedItemStyle>
<AlternatingItemStyle CssClass="GridAlternatingItem"></AlternatingItemStyle>
<ItemStyle CssClass="GridItem"></ItemStyle>
<HeaderStyle CssClass="GridHeader"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="Lot Number">
<ItemTemplate >
<asp:TextBox ID="txtLot" runat="server" Width="100%" Text='<%# DataBinder.Eval(Container, "DataItem.Lot") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
How can I disable that column in the code behind ??
Neither of the following are working
grdRequestTypeItem.Columns[1].IsReadOnly = true;
((BoundField)grdRequestTypeItem.Columns[0]).ReadOnly = true;
((TemplateField)grdRequestTypeItem.Columns[0]).EditItemTemplate = null;
Even if your DataGrid is not in EditMode it displays the TextBox inside the ItemTemplate. Otherwise you use an EditItemTemplate. That's why neither of your solutions work. You have several options:
Put a <asp:Literal> Control into your ItemTemplate
Bind the ReadOnly property of the TextBox to a bool value of your viewModel
from code behind, you have to address the correct control
you could use something like this to reference the textbox within the item template
foreach (GridViewRow row in grdRequestTypeItem.Rows)
{
var txtLot = row.FindControl("txtLot") as TextBox;
txtLog.IsReadOnly = true;
}
You could also use the DataBinding Event on the row instead of looping through the rows like in the answer of #Stealth22
Try this:
<asp:DataGrid ID="grdRequestTypeItem" TabIndex="1" runat="server" CssClass="Grid" AutoGenerateColumns="False" AllowSorting="True" Visible="true"
OnItemDataBound="grdRequestTypeItem_ItemBound">
And then in your code-behind...
protected void grdRequestTypeItem_ItemBound(Object sender, DataGridItemEventArgs e)
{
if((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
TextBox txtLot = e.Item.FindControl("txtLot");
if (txtLot != null)
{
txtLot.ReadOnly = true;
}
}
}
Someone can correct me if I am wrong anywhere, as I work more with GridViews than DataGrids, but as far as I know, the principle is the same.
I have gridview with 4 columns; in column 1 I added a place holder and other 3 columns are boundfields. In column 1 I'm adding radio buttons dynamically using html code by which I am able to select only one radio button. It's working well, but the problem is I am unable to find the radio button control when a button outside of the gridview is clicked.
Please help, I've been stuck on this problem for 4 days.
Thank you in advance.
I used the following code
.aspx File
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" ForeColor="Black" GridLines="Vertical"
onrowdatabound="GridView1_RowDataBound"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:PlaceHolder ID="ph" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="FIRST NAME" DataField="FNAME"/>
<asp:BoundField HeaderText="LAST NAME" DataField="LNAME"/>
<asp:BoundField HeaderText="EMAIL" DataField="EMAIL"/>
<asp:BoundField HeaderText="AGE" DataField="AGE"/>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
<asp:Button ID="btnSave" Text="Save" runat="server" onclick="btnSave_Click1" />
</form>
Code Behind file
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex != -1 && e.Row.DataItem != null)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
RadioButton rb = new RadioButton();
rb.ID = "rbSelect";
holder.Controls.Add(rb);
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
PlaceHolder holder = (PlaceHolder)GridView1.Rows[i].Cells[0].FindControl("ph");
RadioButton rbtn = holder.FindControl("rb") as RadioButton;
if (rbtn.Checked == true)
{
Response.Write("<Script>alert('Radiocheck')</Script>");
}
}
}
It's not clear why you need to create dynamic RadioButtons at all. That makes all just more difficult without a benefit in this case(even if, a nested Repeater or GridView would be easier).
However,
you should not create dynamic controls in RowDataBound since that is triggered only if the GridView was databound. But since by default ViewState is enabled you wouldn't DataBind it on postbacks. Dynamic controls on the other hand must be recreated on every postback.
Therefore create them in RowCreated which is triggered on every postback. But note that you have (of course) no DataItem there since it is null at this stage(even if the grid will be databound).
So you should create cynamic controls in RowCreated but load them from RowDataBound where you can also access them (f.e. via FindControl).
But instead of adding html-control like <input type='radio' you should create and add a RadioButton with an id. Otherwise you won't be able to acess it later, so holder.FindControl("rb") will, be null since it's not a server-control.
Here's the complete modified code:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PlaceHolder holder = (PlaceHolder)e.Row.FindControl("ph");
var rb = new RadioButton();
rb.ID = "RbSample";
rb.Text = "rb";
holder.Controls.Add(rb);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
var rb = (RadioButton)e.Row.FindControl("RbSample");
rb.Checked = row.Field<bool>("SampleActive");
}
}
protected void btnSave_Click1(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rbtn = (RadioButton)GridView1.Rows[i].FindControl("RbSample");
if (rbtn.Checked)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Radiocheck');", true);
}
}
}
It looks like you are doing FindControl with the "value" of the input, but not with the ASP.NET ID of the control, because it has none. Because it's not an ASP.NET control you cannot find it with FindControl.
I also don't know if you can loop through the Controls property of holder, because it's a plain html control. But you can try it out to put a breakpoint on the FindControl line and explore the Controls property of holder.
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);
}
}
}