problem in gridview control of user control - asp.net

My problem is I am setting the datasource from parent page.But if I set disable to certain columns of gridview the event of the controls inside those disabled column template gets fired. Like I have a checkbox in one column, if disable that column from parent page while data binding the check_checked event is being fired.
here my code- user control aspx
<asp:TemplateField HeaderText="Exclude Null" ItemStyle-Width="50px">
<HeaderTemplate>
Exclude Null
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkExNull" OnCheckedChanged="chkExNull_OnCheckedChanged"
AutoPostBack="true" />
</ItemTemplate>
<ItemStyle HorizontalAlign="left" VerticalAlign="Top" />
<HeaderStyle HorizontalAlign="left" VerticalAlign="Top" />
</asp:TemplateField>
.cs file of parent
GridView gvCondition = (GridView)ucCondition.FindControl("gvCondition");
gvCondition.DataSource = ConditionFieldCollection;
gvCondition.Columns[5].Visible = false;
gvCondition.Columns[6].Visible = false;
gvCondition.Columns[7].Visible = false;
gvCondition.Columns[8].Visible = false;
gvCondition.DataBind();
What should I do, and is there any other way through which I can hide some of the columns of grid view control of user control??

Before your DataBind(). write this:
gvCondition.DataBound += new EventHandler(gvwCondition_DataBound);
and write in that method, the code to hide the columns.
Hope that helps.

Related

Copy GridView struture to another GridView

I have about 11 GridViews on my page: GridView1, GridView2, ... GridView10 and GridViewActive.
GridView1 to GridView10 are invisible, but GridViewActive is Visible.
Based on different conditions I need to copy structure of one GridView to GridViewActive.
I need to do something like
//common params
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
CopyGridViewStructure(GridView1, GridViewActive);
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
}
etc.
// DO OTHER STAFF WITH GRIDVIEWATIVE HERE AND IN OTHER METHODS
And on button click (actually it is a bit more complicated than simple ButtonClick, as it is Ajax which calls Button click, and button is actually invisible for user):
//this block doesn't work for now, because grvActive doesn't have any structure
this.grvActive.DataSource = SqlDataSource1;
this.grvActive.DataBind();
I need to copy only Columns. Have not found sollution for this. GridView doesn't contain Clone method.
EDIT:
GridView1 to GridView10 and GridViewActive are not dynamically created.
Example of GridView:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" Visible="false">
<Columns>
<asp:BoundField DataField="username" HeaderText="First Name">
<ItemStyle Width="110px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usersurname" HeaderText="Last Name">
<ItemStyle Width="110"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="usertype" HeaderText="User Type">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Login">
<ItemTemplate>
<asp:Label runat="server" ID="lblLastModifyDate" Text='<%# MyUtility.MyCommon.FormatDate(Eval("logindate").ToString()) %>' />
</ItemTemplate>
<ItemStyle Width="177px"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
Other GridView are very similar, but with different columnnames and datafields. Some of them contains different TemplateField, some doesn't have TemplateFields at all.
I have not found a sollution for copying GridView structure, however, I have found a solution for my problem. Instead of Cloning structure, I am saving GridView ID and then I am using FindControl.
private string GridID
{
get
{
return ViewState["GridID "].ToString();
}
set
{
ViewState["GridID "] = value;
}
}
And then
SqlDataSource1.SelectParameters["CommonParam1"].DefaultValue = this.commonParam1;
if (reportname = "report1")
{
SqlDataSource1.SelectParameters["Param"].DefaultValue = this.param;
// //CopyGridViewStructure(GridView1, GridViewActive);
GridID = "GridView1";
}
else if (reportname = "report2")
{
SqlDataSource1.SelectParameters["AnotherParam"].DefaultValue = this.anotherParam;
CopyGridViewStructure(GridView2, GridViewActive);
GridID = "GridView2";
}
etc.
And when I need to use gridView, I am using FindControl:
GridView grd = (GridView) this.FindControl(GridID);
// actually for my page I am using masterpage and FindControl is a bit more complicated:
GridView grd = (GridView)((ContentPlaceHolder)(this.Controls[0].FindControl("mainContent"))).FindControl(GridID);
I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page.
if you need some css style don't forget of add them in destination page

ASP.NET Gridview: How do I stop a <span></span> within a Gridview from resetting when posting back?

I have a Gridview which contains some controls which are updated from the server when the user makes a selection from a gridview.
After making their selection from a drop down list the user can enter a percentage into a textbox on a row and I have some javascript which then carries out some calculations and outputs to a span within an item template in the Gridview.
This all works but if the user then makes another drop down list selection on any row all the spans in the gridview are reset to blank (I've tried with various controls, both asp.net and html).
This is all inside an Update Panel.
Code:
<asp:GridView runat="server" ID="gdvIngredients" AutoGenerateColumns="false" CssClass="table table-stripped"
GridLines="None" Visible="false" ShowFooter="true" EnableViewState="true">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label runat="server" ID="lblId" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Ingredient" ItemStyle-Width="12%">
<ItemTemplate>
<asp:DropDownList runat="server" ID="ddlName" AutoPostBack="true" OnSelectedIndexChanged="ddlName_SelectedIndexChanged"
ForeColor="Black" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="%" ItemStyle-Width="6%">
<ItemTemplate>
<asp:TextBox runat="server" Text="0" Width="50px" ID="txtPercentage" onkeyup="calculate(this);"
ForeColor="Black" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="kj" ItemStyle-Width="6%">
<ItemTemplate>
<asp:Label runat="server" ID="lblKj" CssClass="Kj" Style="display: none;" />
<span runat="server" id="spnKj" class="NewKj">0</span>
</ItemTemplate>
From your question what i have understood is that you are doing calculation in javascript and assigning it to span,but when next postback happens the value is not retained...If i am right i would suggest you to try the following steps.Use HiddenFields also to assign Values as HiddenFields Retain values during PostBacks.
Add Hidden field in Item Template
Set "calculate" function to Textbox from Codebehind(from rowdatabound event) & also pass the currosponding HiddenField Value to it as calculate(this,'HiddenFieldId');
protected void grd_RowDataBound(object sender,GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField hdn = ((HiddenField)e.Row.FindControl("HiddenFieldID"));
TextBox txtPercentage = (TextBox)e.Row.FindControl("txtPercentage");
HtmlGenericControl spnKj=(HtmlGenericControl )e.Row.FindControl("spnKj");
txtPercentage.Attributes["onClick"]="calculate(this,'"+hdn .ClientID+"');"
spnKj.innerHTML=hdn.Value;
}
}
Javascript:
Assign Calculated Value to Hidden Field...
function calculate(hdnID)
{
var CalcValue=//do your Calculation
document.getElementByID(hdnID).Value=CalcValue;
}
3.In the DropDown PostBack Event Bind the GridView Again.
The above code should take care of the Issue You are facing.
You can use the "AutoPostBack" property to control the Postback event of some controls.
Have a look if your dropdown list selection do any PostBack.
If it does, then span values disappear, becuase Span is not ASP.NET webcontrol. After pages is postback, asp.net webcontrol values are restored from ViewState. So, spans doesn't have ViewState and no values are restored.
You can try to change your tag to
<span runat="server" id="spanIDHere">SomeValue here</span>
runat="server" makes span to be HtmlGenericControl and maintains its ViewState.
Span values would not be saved after postback if you update them using Javascript. You should call server-side function to update span values or try to use Hidden fields to store your values.

GridView loses column contents during PostBack

I am having an issue with the behavior of a GridView between post backs.
The real problem comes from a TemplateField I define in the markup at column[0] with a child CheckBox control. Things work fine for the first, and second search executions. However, at some point between the second execution and anything that causes a post back there after, I lose the contents of the TemplateField.
Its only the the contents of the column and not the whole column itself that gets removed. The TemplateField is present in the source and shows a formated column at position 0 of the table.
CODE:
protected void ExecuteSearch(object sender, EventArgs e)
{
if (lb_SelectedFields.Items.Count == 0) { return; } //if no selected fields
//Generates custom SQL query based on user inputs and column Selections
BuildQuery(); // sets txbSqlText.Text = to the SQL string
DataTable Table = SqlAdapter.Select(new System.Data.SqlClient.SqlCommand(txbSqlText.Text));
for (int i = gv_SearchResults.Columns.Count - 1; i > 0; i--)
{ gv_SearchResults.Columns.RemoveAt(i); } //removes all the columns except[0]
foreach (ListItem Item in lb_SelectedFields.Items) //adds all the user defined columns
{
//Column object that is able to find the column definition
Column Col = ColumnsBasedOnFocus.FindColumName(Item.Value);
if (Col.Type == "HyperLink") { gv_SearchResults.Columns.Add(CreateHyperLinkField(Col)); }
else { gv_SearchResults.Columns.Add(CreateBoundColumn(Col, true)); } //true is if the column is visable
}
gv_SearchResults.DataSource = Table;
gv_SearchResults.DataBind();
}
ASP.NET:
<asp:GridView ID="gv_SearchResults" runat="server" GridLines="None" CellSpacing="0"
CellPadding="0" AutoGenerateColumns="false" CssClass="TABLE_LIGHTBLUE" Width="100%">
<HeaderStyle CssClass="TABLE_LIGHTBLUE_HEADERROW" />
<Columns>
<asp:TemplateField ItemStyle-Width="30" ItemStyle-Wrap="false">
<HeaderTemplate>
<center>
<asp:Button ID="btn_SelectAll" runat="server" OnClick="SelectAll" Text="All" CssClass="TEXT_SMALL" />
<asp:CheckBox ID="chk_Placeholder" runat="server" Visible="false" /></center>
</HeaderTemplate>
<ItemTemplate>
<center>
<asp:CheckBox ID="chk_Select" runat="server" Visible="true" />
<asp:Label ID="lbl_AssetGID" runat="server" Visible="false" Text='<%# Bind("i_GID") %>' /></center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Found a link that describes a similar situation.
https://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted#details
They describe a bug in ASP.Net code that fails to properly manage view states with template fields in dynamically generated grid views.
Basically TemplateFields can't be properly restored from ViewState, and if you modify the ASPX-declared columns programmatically, it can't create them from the declarations either.
The only solution I could get working was to create a new class deriving from TemplateField that in the constructor set the ItemTemplate to an ITemplate-derived class, which means having to define the template programmatically instead of declaratively.
You can also rebind the gridview on each postback but that's its own can of worms.

How to enable/disable the row double click editing property of radgrid based on condition

I have the following code
Javascript
function RowDblClick(sender, eventArgs)
{
window.radopen("SourceFileAdmin.aspx?SourceSystemFileId=" + eventArgs.getDataKeyValue("SourceSystemFileId"), "UserListDialog");
}
Aspx Grid Code
<telerik:RadGrid ID="RadGrid" runat="server" AllowPaging="True" AllowSorting="True"
GridLines="None" ShowGroupPanel="True" Skin="Black" AutoGenerateColumns="False"
Width="100%" AllowAutomaticInserts="false" AllowAutomaticUpdates="false" PagerStyle-Mode="NumericPages"
OnItemInserted="GridItemInserted"
onitemdatabound="GridItemDataBound">
.............................................
........................................
..................................................
<ClientSettings>
<Selecting AllowRowSelect="true" />
<ClientEvents OnRowDblClick="RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
<asp:Button ID="AddSrcButton" runat="server" Text="Add New" OnClientClick="return ShowInsertForm();" />
My actual question is to disable or enable RowDblClick property based on the user permission
This is my sample code in the aspx.cs file where i want to set the edit or view permission for radgrid
this.AddSrcButton.Enabled = this.Privilige.CanModify;//the value will be true or false
this.RadGrid.Enabled=this.Privilige.CanModify;
//the value will be true or false ,based on this value i want to enable/disable my rowdblclick,can any one help out to figure out where i am doinfg wrong
You can set the row double click on the server side programatically
if(!this.Privilige.CanModify)
RadGrid.ClientSettings.ClientEvents.OnRowDblClick = "";
Beware though to renable the page you will probably need to refresh it all to get the clientside javascript to be loaded again, unless you move that into the .cs file

Hiding ItemTemplate in gridview

I have this code in .aspx page
<gridview .....
<columns>
............
...........
<asp:templatefield Visible="true" headertext="Title" >
<edititemtemplate>
<asp:checkbox id="chkTitle" runat="server" />
</edititemtemplate>
</asp:templatefield>
<asp:commandfield buttontype="Link" edittext="Edit" showeditbutton="true"/>
</columns>
</gridview>
i only want to show the column when the user clicks on Edit button to edit the row.
In your GV Data Bound Event Handler (not row data bound):
For i As Integer = 0 To GridView1.Rows.Count - 1
If GridView1.EditIndex = -1 Then
GridView1.Rows(i).Cells(0).Visible = False
else
GridView1.Rows(i).Cells(0).Visible = true
end if
Next
If GridView1.EditIndex = -1 Then
GridView1.HeaderRow.Cells(0).Visible = False
End If
Source
Code such as GridView.Columns[9].Visible = false; should work - only thing is that grid data-bind must happen after this line. In case you are relying on the view-state for binding the grid in post-back scenarios then you may try putting GridView.DataBind() after you set the column visibility.
Yet another harder way is to set visibility at cell levels in RowDataBound event - see this article that is using this technique.

Resources