I have a RadGrid which on RowClick should send a specific value to the server. Due to the nature of the page all events are handled Server Side. My -Radgrid1- uses a default "select" all sqldatasource when first accessing the page and then, you can filter RadGrid1 items by clicking on another RadGridAnother. which also has a list of different categories.
What happens is :
1. Row is clicked
2. radgrid1_ItemCommand(...,...) is executed.
Code Below changed to actual after Edit :
protected void MenuKampionati_ItemClick(object sender, RadMenuEventArgs e)
{
Case = 2;
Arg1 = "%%";
Arg2 = e.Item.Value;
string query = "EXECUTE get_ndeshje_kot31 " + Case.ToString() + ", '" + Arg1 + "', '" + Arg2 + "', 0";
SqlDataSource MyDataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings["basteConnectionString"].ConnectionString, query);
this.GridNdeshjet.DataSource = MyDataSource;
this.GridNdeshjet.DataBind();
}
3. Page "refreshes" and RadGrid1 has the Old values in it + the label has default text of test.
I have read all Telerik API regarding this matter, and tried previuos solutions in vain.
Is there something I am missing? or forgetting to do? Has anyone any idea why this might be happening?
Regarding AJAX, my manager has instructed me not to "AJAX" this page. Hope my english is good enough for this problem.
Edit : I got a PM about my query, i have already tested it in sqlserver management studio and it is fully functional. I am now adding aspx code of the div that contains this controls, outside there are labels, some aspbutton and nothing more not related to the contents of this div.
Second Edit, Previous Grids were changed to RadMenu. Codebehind is still the same, just associated with the new Menu.
<div>
<table>
<tr>
<td><asp:UpdatePanel ID="panelGetTeGjitha" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" >
<ContentTemplate>
<telerik:RadMenu ID="MenuKategoria" runat="server" DataSourceID="GetKategoriaDataSource"
DataTextField="kategoria" DataValueField="vlera" Flow="Vertical"
DataFieldID="kategoria"
onitemclick="MenuKategoria_ItemClick">
</telerik:RadMenu>
<asp:SqlDataSource ID="GetKategoriaDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:basteConnectionString %>"
SelectCommand="Get_Kategorite" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter DefaultValue="0" Name="Country" SessionField="country"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel></td>
<td><asp:UpdatePanel ID="panelGetKampionati" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" >
<ContentTemplate>
<telerik:RadMenu ID="MenuKampionati" runat="server" DataSourceID="GetKampionatiDataSource"
DataTextField="kampionati" DataValueField="kampionati" Flow="Vertical"
DataFieldID="kategoria" onitemclick="MenuKampionati_ItemClick" >
</telerik:RadMenu>
<asp:SqlDataSource ID="GetKampionatiDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:basteConnectionString %>" SelectCommand="SELECT kampionati FROM ndeshje (NOLOCK)
WHERE ((data > getdate() and ndeshje_id_live IS NULL) OR (data < getdate() AND data_hapjes > getdate() AND ndeshje_id_live IS NOT NULL))
AND bllokuar = '0' AND live = 0
GROUP BY kampionati ORDER by kampionati"></asp:SqlDataSource>
<telerik:RadGrid ID="GridNdeshjet" runat="server" GridLines="None"
onneeddatasource="GridNdeshjet_NeedDataSource1">
</telerik:RadGrid>
</ContentTemplate>
</asp:UpdatePanel></td>
<td><asp:UpdatePanel ID="panelGetNdeshje" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false" >
<ContentTemplate>
<telerik:RadMenu ID="MenuNdeshjeLive" runat="server" DataSourceID="GetNdeshjeLiveDataSource"
DataTextField="Home" DataValueField="Home" Flow="Vertical"
DataFieldID="Home" onitemclick="MenuKampionati_ItemClick" >
</telerik:RadMenu>
<asp:SqlDataSource ID="GetNdeshjeLiveDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:basteConnectionString %>" SelectCommand="SELECT MAX(Home) AS Home, MAX(Away) AS Away FROM ndeshje (NOLOCK)
WHERE(Data < getdate() AND data_hapjes > getdate() AND ndeshje_id_live IS NOT null AND live = 1)
AND bllokuar = '0' GROUP BY Home, Away ORDER BY Home, Away"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel></td>
</tr>
</table>
Let me know if any concern.
<asp:UpdatePanel ID="panelGetKampionati" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<telerik:RadMenu ID="MenuKampionati" runat="server" DataTextField="Name" DataValueField="ID"
Flow="Vertical" DataFieldID="ID" OnItemClick="MenuKampionati_ItemClick">
</telerik:RadMenu>
<telerik:RadGrid ID="GridNdeshjet" runat="server" GridLines="None" OnNeedDataSource="GridNdeshjet_NeedDataSource1">
</telerik:RadGrid>
</ContentTemplate>
</asp:UpdatePanel>
..........
protected void MenuKampionati_ItemClick(object sender, RadMenuEventArgs e)
{
GridNdeshjet.Rebind();
}
protected void GridNdeshjet_NeedDataSource1(object sender, GridNeedDataSourceEventArgs e)
{
string strID = string.Empty; // just For Test
if (MenuKampionati.SelectedItem != null)
{
// Get Selected Records as per item selected in RadMenu
//Case = 2;
//Arg1 = "%%";
string Arg2 = MenuKampionati.SelectedItem.Value;
//string query = "EXECUTE get_ndeshje_kot31 " + Case.ToString() + ", '" + Arg1 + "', '" + Arg2 + "', 0";
//SqlDataSource MyDataSource = new SqlDataSource(ConfigurationManager.ConnectionStrings["basteConnection
strID = MenuKampionati.SelectedItem.Value; // just For Test
}
else
{
// Get All records From DB
}
// just For Test
dynamic data = new[] {
new { ID = 1, Name ="Name" + strID},
new { ID = 2, Name ="Name"+ strID},
new { ID = 3, Name ="Name"+ strID},
new { ID = 4, Name ="Name"+ strID},
new { ID = 5, Name ="Name"+ strID},
new { ID = 6, Name = "Name"+ strID}
};
GridNdeshjet.DataSource = data;
}
Related
I am trying to add RadCombobox to a telerik:GridTemplateColumn as a FilterTemplate control. I have multiple columns and all have RadCombobox with same filter values.
<telerik:GridTemplateColumn AutoPostBackOnFilter="true" HeaderStyle-Width="90px"
UniqueName="Date1" HeaderText="Date1" DataField="Day1">
<FilterTemplate>
<telerik:RadComboBox ID="RadComboBoxDate1" Height="90px" AppendDataBoundItems="true"
Width="105px" runat="server" OnClientSelectedIndexChanged="Date1IndexChanged">
</telerik:RadComboBox>
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function Date1IndexChanged(sender, args) {
var tableView = $find("<%# TryCast(Container,GridItem).OwnerTableView.ClientID %>");
var selectedValue = sender.get_value();
if (selectedValue) {
if (parseInt(selectedValue) < 0) {
tableView.filter("Date1", selectedValue, "NoFilter");
}
else { tableView.filter("Date1", selectedValue, "EqualTo");
}
}
}
</script>
</telerik:RadScriptBlock>
</FilterTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblday1"></asp:Label>
<asp:HiddenField ID="hdDay1" runat="server" Value='<%# DataBinder.Eval(Container.DataItem,"Day1") %>' Visible="false" />
</ItemTemplate>
</telerik:GridTemplateColumn>
I have 7 such columns and I want to use a single RadCodeBlock to handle the filter. Is there any better way to do this?
Solution given on Telerik website worked for me
http://www.telerik.com/forums/how-to-get-column-name-from-filter-template-control-s-js-event
I have product list and I should to filter products by multiple criterias. In one page I have multiple criterias (name, price, create date etc.) in differenet elements: textbox, Dropdownlist etc.
I want to search products without reload page. When I change any criteria, product list updates automatically, without reloading page. Like this: Filter users.
Here is my view:
#model IEnumerable<Product>
<section id="sidebar left">
<div class="form_info">
<label>Category</label>
#Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as IEnumerable<SelectListItem>, "-", new { id = "ProductCategory" })
</div>
<div class="form_info">
<label>Name</label>
#Html.TextBoxFor(model => model.Name, new{ id = "ProductName"})
</div>
...//other properties
</section>
<section id="content" >
#foreach (var item in Model)
{
<a class="productStyle" href="#Url.Action("Details", "Product", new { id=item.Id})">#item.Name</a>
}
</section>
I have FilterProductByCriteria(int CategoryId, int Name, double priceFrom, double PriceTo..etc) action in controller.
I can do this: in onchange() event of every element to send all criteria values to controller and call back result data - filtered product list, but I cannot use returned data in #foreach (var item in Model). Help me in it or advice better ways, please. (Sorry for bad english)
I can do this: in onchange() event of every element to send all
criteria values to controller and call back result data - filtered
product list, but I cannot use returned data in #foreach (var item in
Model)
Why not? Sure you can. As an alternative you could place the filter criteria inputs inside an HTML form and provide a submit button that will send the values to the controller and this controller will return the same view with filtered products model. And then you could optimize this by introducing AJAX. You would place the <section id="content"> contents into a partial view which will contain the filtered results. And then you could use an Ajax.BeginForm instead of a regular Html.BeginForm to send the filter criteria to the controller action. In turn this controller action will perform the filtering and pass the filtered product list to the same partial view (return PartialView()) which will then be used to refresh only results section of your DOM.
For example:
#model IEnumerable<Product>
#using (Ajax.BeginForm("Search", "SomeController", new AjaxOptions { UpdateTargetId = "content" }))
{
<section id="sidebar left">
<div class="form_info">
#Html.LabelFor(model => model.CategoryId)
#Html.DropDownListFor(
model => model.CategoryId,
ViewBag.CategoryList as IEnumerable<SelectListItem>,
"-",
new { id = "ProductCategory" }
)
</div>
<div class="form_info">
#Html.LabelFor(model => model.Name)
#Html.TextBoxFor(model => model.Name, new { id = "ProductName"})
</div>
...//other properties
</section>
<button type="submit">Filter</button>
}
<section id="content">
#Html.Partial("_Products", Model)
</section>
and then your controller action might look like this:
[HttpPost]
public ActionResult Search(SearchCriteriaViewModel model)
{
IEnumerable<Product> filteredProducts = ... you know what to do here
return PartialView("_Products", filteredProducts);
}
Please refer this link for searching inside ASP.Net GridView without refresh the page.
[ASP.NET GridView Searching without refresh whole Page]
http://www.ashishblog.com/search-sort-in-gridview-using-c-net-ajax-and-jquery/
Here is my aspx page having search text box and gridview inside AJAX update panel.
<asp:ScriptManager ID="ScriptManager" runat="server" />
Search: <asp:TextBox ID="txtSearch" runat="server" OnTextChanged="txtSearch_TextChanged" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="GridviewDiv">
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
AllowSorting="true" DataSourceID="dsGridview" Width="540px" PageSize="10" CssClass="yui">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" ItemStyle-Width="40px"
ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblFirstname" Text='<%# HighlightText(Eval("FirstName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemStyle Width="120px" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblLastname" Text='<%# HighlightText(Eval("LastName").ToString()) %>' runat="server"
CssClass="TextField" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department"
ItemStyle-Width="130px" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
ItemStyle-Width="130px" />
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
--> Here is my code behind file add method in page load event.
string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", "setTimeout('__doPostBack(\\'" + txtSearch.ClientID.Replace("_", "$") + "\\',\\'\\')', 0);");
if (!IsPostBack)
{
Gridview1.DataBind();
}
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchString = txtSearch.Text;
}
public string HighlightText(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
// Highlight keywords by calling the
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
// Set the RegExp to null.
RegExp = null;
}
public string ReplaceKeyWords(Match m)
{
return "<span class=highlight>" + m.Value + "</span>";
}
I am trying to create ajax tabs dynamically and storing their ID's in a session. I am getting an error "Specified argument was out of the range of valid values.
Parameter name: value". I am able to create the first tab by invoking the click button event. When I click the button and invoke the same event on the second try...I get the error. Seems like I am referencing a tab ID or container\tab that is no longer defined or contained in session?
I have researched this thoroughly and can't seem to find the answer. Any help would be greatly appreciated.
I have the correct scriptmanager and assembly references on my asp page. Here is the asp code and the code behind snippet.
<div>
<asp:Button ID ="AddTab" Text="Add Tab" OnClick = "addTab_Click" runat="server"/>
<AjaxToolkit:TabContainer ID="TabContainerContent" runat="server" Height="150px" BackColor="White" AutoPostBack="True"
OnActiveTabChanged="TabContainerContent_OnActiveTabChanged" >
</AjaxToolkit:TabContainer>
<asp:Label ID="currentTabIndex" runat="server"></asp:Label>
</div>
</td>
Code Behind
private List<string> dynamicTabIDs;
protected void Page_Init(Object sender, EventArgs e)
{
if (Session["dynamicTabIDs"] != null)
{
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
foreach (string tabID in dynamicTabIDs)
{
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = tabID;
tab.HeaderText = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
Label tabContent = new Label();
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
tab.Controls.Add(tabContent);
TabContainerContent.Tabs.Add(tab);
}
}//end if
else
{
dynamicTabIDs = new List<string>();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
Session["dynamicTabIDs"] = dynamicTabIDs;
}
protected void TabContainerContent_OnActiveTabChanged(object sender, EventArgs e)
{
currentTabIndex.Text = TabContainerContent.ActiveTab.ID;
}
public void addTab_Click(object sender, EventArgs e)
{
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
tab.ID = "tab" + Convert.ToString(TabContainerContent.Tabs.Count);
tab.HeaderText = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
Label tabContent = new Label();
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
tab.Controls.Add(tabContent);
TabContainerContent.Tabs.Add(tab);
TabContainerContent.ActiveTab = tab;
dynamicTabIDs.Add(tab.ID);
}
I tried a different approach to accomplsih this. I created static tabs and just set them to visible true/false depending if they are used or not. I couldn't get dynamic tabs to work. I did have to restrict the number of customer numbers to 15 orders with this approach.
I found that it was very easy to bind data to a gridview within Ajax tabs. Of course you needed you script manager ajax reference declared in the asp page and ajax reference update to web.config file. You also need to add the ajax css style to an existing style sheet. i tried using a seperate one and it didn't work.
ASP HTML
<AjaxToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0"
Visible="false" ScrollBars="Both"
CssClass="Tab2" Width="1326px" Height="464px" >
<AjaxToolkit:TabPanel ID="TabPanel1" runat="server" HeaderText="Empty" Enabled="true" ScrollBars="Both" CssClass="Tab2">
<ContentTemplate>
<div style="overflow:auto;width:1287px; height: 418px;">
<font color="white" size="1" face="Verdana">
<asp:GridView ID="SalesOrderView1" runat="server" BackColor="White" BorderColor="#DEDFDE"visible="False"BorderStyle="None" BorderWidth="1px"
CellPadding="4" ForeColor="Black"
GridLines="Vertical" HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
</div>
</font>
</ContentTemplate>
</AjaxToolkit:TabPanel>
<AjaxToolkit:TabPanel ID="TabPanel2" runat="server" HeaderText="Empty" ScrollBars="Both" CssClass="Tab2">
<ContentTemplate >
</AjaxToolkit:TabContainer>
C# Code to bind data to the gridview on click button event.
SalesOrderView1.Visible = true;
TabPanel1.Visible = true;
TabPanel1.HeaderText = Order_List[multi_order_count];
How can I resize the RadChart of Telerik for asp ajax to the full width of the screen?
I found on the Telerik forum someone who opens a popup full screen containing your RadChart.
Look at the end, there is some code available : Telerik Forum
This is what I came up with and it works fine for me
C# code on the server
public void buttonUpdate_Click(object sender, EventArgs args)
{
this.radChart1.Visible = true;
this.radChart1.Width = Int32.Parse(this.hiddenFieldWidthInPixels.Value);
}
html and javascript on the client
<asp:UpdatePanel runat="server" ID="updatePanel" OnLoad="wtf" UpdateMode="Conditional">
<ContentTemplate>
<panel>
<asp:Button runat="server" ID="buttonUpdate" style="width:80%; height:10%; visibility: collapse; " Text="This is the update button and should not be visible" OnClick="buttonUpdate_Click" />
<asp:HiddenField runat="server" ID="hiddenFieldWidthInPixels" />
<telerik:RadChart runat="server" ID="radChart1" Visible="false" />
</panel>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function getASPElm(nm) {
if ($get(nm)) return $get(nm);
var e = document.getElementsByTagName('*');
for (var i = 0; i < e.length; i++) {
if (e[i].id) {
if (e[i].id.indexOf(nm) != -1) return e[i];
}
}
return null;
//http://forums.asp.net/t/1107047.aspx/1
}
var buttonUpdate = getASPElm('buttonUpdate');
var hiddenField = getASPElm('hiddenFieldWidthInPixels');
hiddenField.value = buttonUpdate.style.pixelWidth;
buttonUpdate.click();
</script>
And I also found this link on Telerik's site with another approach
link
LaGrandMere, thanks for the help, but the provided link did not really address mu issue.
I am working on extending an ASP.NET 2.0 application using an InterBase database. My experience is in PHP/MySQL, so my familiarity with ASP is currently in the 2-week range, and is pieced together from examining a co-worker's code, the first 90 pages of my ASP book, and Google. In the application, I have an SqlDataSource control connecting to my database and selecting the information I need. Then the results are copied into a DataView where I modify the data in one of the columns, and then I push that DataView to a GridView for output. The issue I'm having is that I cannot sort the GridView at this point. I followed instructions here: http://forums.asp.net/p/956540/1177923.aspx, but to no avail.
Here is the page code:
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="Products" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
ProviderName="<%$ ConnectionStrings:ConnectionString1.ProviderName %>" OnLoad="ProductsDS_Load"
OnSelected="ProductsDS_Selected" DataSourceMode="DataSet">
</asp:SqlDataSource>
<br />
<asp:Label ID="testlabel" runat="server"></asp:Label>
<br />
<asp:Label ID="testlabel2" runat="server"></asp:Label>
<br /><br />
This table lists all 2000+ numbered projects which are at least partially in process.<br />
The Project number link leads to a more detailed view of that project.<br />
<br />
<asp:Label runat="server" ID="numrows"></asp:Label> results returned.
<br />
<asp:GridView ID="ProductsView" runat="server" EnableModelValidation="True"
AutoGenerateColumns="False" CellPadding="4" OnSorting="ProductsView_Sorting"
ForeColor="#333333" GridLines="None" AllowSorting="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:HyperLinkField HeaderText="Project" SortExpression="PROJECT"
DataTextField="PROJECT" Target="subweeklyreport" DataNavigateUrlFields="PROJECT"
DataNavigateUrlFormatString="Products.aspx?p={0}" />
<asp:BoundField Visible="false" DataField="PROJECTID" />
<asp:BoundField DataField="PART" HeaderText="Part #"
SortExpression="PART" />
<asp:BoundField DataField="DESCRIPTION" HeaderText="Description"
SortExpression="DESCRIPTION" />
<asp:BoundField DataField="ENGMGR" HeaderText="Eng. Mgr."
SortExpression="ENGMGR" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
</form>
And here is the code behind:
protected void ProductsDS_Load(object sender, EventArgs e)
{
string SQLQuery = Query would go here;
testlabel2.Text = SQLQuery;
Products.SelectCommand = SQLQuery;
Products.DataBind();
DataView dv = (DataView)Products.Select(new DataSourceSelectArguments());
foreach (DataRow dr in dv.Table.Rows)
{
string name = dr["ENGMGR"].ToString();
string[] explode = name.Split(' ');
string newname;
if (explode.Length == 3)
{
newname = explode[2] + ", " + explode[0];
}
else
{
newname = explode[1] + ", " + explode[0];
}
dr["ENGMGR"] = newname;
//testlabel.Text = dr["ENGMGR"].ToString();
}
Products.DataBind();
//ProductsView.DataSourceID = "Products";
ProductsView.DataSource = dv;
ProductsView.DataBind();
ProductsView.Enabled = true;
ProductsView.Visible = true;
}
protected void ProductsDS_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
numrows.Text = e.AffectedRows.ToString();
}
protected void ProductsView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ProductsView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
ProductsView.DataSource = dataView;
ProductsView.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
What I think is happening is that whenever the GridView does the postback for the sort, it causes the query to be executed again and overwrite the attempt to sort the existing data in the GridView, but I don't know enough about ASP right now to prevent this behavior. Any help would be much appreciated.
I ended up solving my own problem. I created a session variable to store the dataview between page loads, and checking to see if the dataview is stored before executing the query, and sorting it if it is, and just performing the regular query otherwise. Since I don't expect data to be introduced between the initial page view and the sort, I don't think using a stored copy of the data would be a major issue.