ASP.NET how to make OnRowDataBound event asynchronous? - c#

I currently have a nested datagrid. The top-level grid gets data from a stored procedure. The nested grid gets data from a stored procedure based on the column value of each row.
Here is my ASPX code
<%# Page Language="C#" Async="true" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="CS" Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
* {
margin:0;
padding: 0;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).attr("src", "images/minus.png");
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "images/plus.png");
$(this).closest("tr").next().remove();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="ID" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" width="25px" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="135px" DataField="Label" HeaderText="Label" />
<asp:BoundField ItemStyle-Width="150px" DataField="IDs" HeaderText="IDs" />
<asp:BoundField ItemStyle-Width="150px" DataFormatString="${0:###,###,###.00}" DataField="Total" HeaderText=Total" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="Source" HeaderText="Source" />
<asp:BoundField ItemStyle-Width="150px" DataField="Label" HeaderText="Label" />
<asp:BoundField ItemStyle-Width="150px" DataFormatString="${0:###,###,###.00}" DataField="Total20" HeaderText="Total20" />
<asp:BoundField ItemStyle-Width="150px" DataFormatString="${0:###,###,###.00}" DataField="Total1" HeaderText="Total1" />
<asp:BoundField ItemStyle-Width="150px" DataFormatString="{0:P1}" DataField="Average_Fee_PCT" HeaderText="Average Fee" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Here is C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class CS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<script>console.log('Page Loaded');</script>");
if (!IsPostBack)
{
gvCustomers.DataSource = GetData("exec ReturnData '" + DateTime.Now.ToString("yyyy-MM-dd") + "'");
gvCustomers.DataBind();
}
}
private static DataTable GetData(string query)
{
using (SqlConnection con = new SqlConnection("Data Source=SQLSERVER;Initial Catalog=DBNAME;User Id=user;Password=pass"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
Response.Write("<script>console.log('Next Column...." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "');</script>");
if (e.Row.RowType == DataControlRowType.DataRow)
{
Response.Write("<script>console.log('Pulling data...." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "');</script>");
string ID = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
gvOrders.DataSource = GetData(string.Format("exec ReturnDataSingle '" + ID + "', '"+ DateTime.Now.ToString("yyyy-MM-dd") + "'"));
gvOrders.DataBind();
Response.Write("<script>console.log('Pulled data...." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "');</script>");
}
}
}
Currently, after each top-level row is created, it runs a stored procedure and returns the data as a nested gridview.
Each time the stored procedure runs for the nested grid view, it takes 200ms for it to return the data. The issue is that with 3 or 4 rows it is pretty fast. But when I have 300 rows, it will take 1 minute for the page to fully load.
Are there any ways I can change it so it won't wait until the current row is completed before moving onto the next row?

Related

C# asp.net checkbox not firing when unchecked

I have found this question a few places but no solutions...
I have a checkbox in a gridview:
<asp:TemplateField HeaderText="Closed?">
<ItemTemplate >
<asp:CheckBox ID="Status_CB" runat="server" AutoPostBack="true"
OnCheckedChanged="Status_CB_CheckedChanged"
EnableViewState="true" ViewStateMode="Enabled"
Checked='<%# Convert.ToString(Eval("cStatus")) == "1" ? true : false %>'/>
</ItemTemplate>
</asp:TemplateField>
codebehind:
protected void Page_Load(object sender, EventArgs e) {
if (!int.TryParse(Session["FacilityID"].ToString(), out FId)) {
FId = 0;
}
if (!Page.IsPostBack) {
if (!string.IsNullOrEmpty(Request.QueryString.Get("WorkCenter"))) {
wc = Request.QueryString.Get("WorkCenter");
WorkcenterHeader.InnerText = wc + " Schedule ";
HiddenWorkCenter.Value = c;
}
if (!SQLHasData()) {
SavePrioritiesToSQL();
}
BindGrid();
}
}
protected void Status_CB_CheckedChanged(object sender, EventArgs e) {
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow) cb.Parent.Parent;
}
When i check the box originally, it works. When i uncheck it, the breakpoint i have on the first line of Status_CB_CheckedChanged does not fire at all.
What am i missing any one know?
UPDATE - here is the table, it is nested. i wonder if that is the reason it will not call the postback on uncheck...
UPDATE - ok i gave up, this must be a bug with nested gridview in asp so if you have a nested gridview, i recommend not using checkboxes. I switched mine to a text field of the cStatus "open" or "closed" and use a button with a command argument that is the row index:
<asp:GridView ID="JobInfo_GV" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid2" OnRowCommand="JobInfo_GV_RowCommand">
<asp:BoundField DataField="cStatus" HeaderText="Status" ReadOnly="True" HeaderStyle-CssClass="center-row" ItemStyle-CssClass="center-row"/>
<asp:TemplateField HeaderText="Update">
<ItemTemplate >
<asp:Button id="UpdateClosed" commandname="Select" buttontype="button" Text="ToggleStatus" runat="server" CommandArgument='<%# Container.DataItemIndex %>'/>
</ItemTemplate>
</asp:TemplateField>
then the C#:
protected void JobInfo_GV_RowCommand(object sender, GridViewCommandEventArgs e) {
var grid = (GridView)sender;
var errorMessage = string.Empty;
if (grid != null) {
int index = 0;
if (int.TryParse(e.CommandArgument.ToString(), out index) ){
GridViewRow row = grid.Rows[index];
I just created a project and reused your code as part of it.
It works as you expect:
Note you need to set AutoPostBack="true" for the Checkbox control
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GV" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name">
</asp:BoundField>
<asp:TemplateField HeaderText="Closed?">
<ItemTemplate>
<asp:CheckBox ID="Status_CB" runat="server" AutoPostBack="true"
OnCheckedChanged="Status_CB_CheckedChanged"
EnableViewState="true" ViewStateMode="Enabled"
Checked='<%# Convert.ToString(Eval("cStatus")) == "1" ? true : false %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
And the Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindGrid();
}
public class DataS
{
public int cStatus { get; set; }
public string Name { get; set; }
}
private void BindGrid()
{
List<DataS> list = new List<DataS>() { new DataS() { Name = "Name1", cStatus = 1 }, new DataS() { Name = "Name2", cStatus = 1 }, new DataS() { Name = "Name3", cStatus = 0 } };
GV.DataSource = list;
GV.DataBind();
}
protected void Status_CB_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.Parent.Parent;
}
}
}

fileupload control only uploading 1 file

I am trying to make the upload control upload multiple files, but it is only uploading one and I am not sure why. Also I want to call the stored proc if, and only if, all required files have successfully been uploaded. Any suggestions would be helpful as I am at a loss. im sure its something im doing wrong within my foreach loop but I am unsure what exactly it is.
My markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Admin/AdminMaster.master" AutoEventWireup="true" CodeFile="addFont.aspx.cs" Inherits="Admin_addFont" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"></asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightCol" runat="Server">
<h1>Fonts</h1>
<h2>Currently available fonts</h2>
<div><asp:Label ID="lblFontGrd" runat="server"></asp:Label>
<asp:GridView ID="grdFonts" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnPageIndexChanging="grdFonts_PageIndexChanging">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="ID" FooterText="ID" HeaderText="ID">
<ItemTemplate>
<asp:Label ID="fontId" runat="server" Text='<%# Eval("FontId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Font Name" FooterText="Font Name" HeaderText="Font Name">
<ItemTemplate>
<asp:Label ID="lblfontName" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblfontNameEdit" runat="server" Text='<%# Eval("FontName") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Example" FooterText="Example" HeaderText="Example">
<ItemTemplate>
<asp:Label id="lblfontExample" runat="server" Font-Size="Large" Font-Names='<%# BuildFont(Eval("FontFamily").ToString()) %>' ><h3>This is an example of the font</h3></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Discontinued?" HeaderText="Discontinued?" FooterText="Discontinued?">
<ItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="false" />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="Discontinued" runat="server" Checked='<%# Eval("Discontinued") %>' Enabled="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<span onclick="return confirm('Are you sure you want to delete?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</div>
<div>
<h2>Add a new font</h2>
<asp:Label ID="lblUpload" runat="server" ForeColor="Red"></asp:Label>
<p>In order to add a new font to the library please follow the steps laid out below:</p>
<p><strong>Step 1: </strong> The first, and most important, thing to do is make sure you have the appropriate license to use your font for print and web.</p>
<p><strong>Step 2: </strong> Next you need to convert your font file into multple formats to ensure browser compatability.
To do so please follow <a target="_blank" href="http://www.fontsquirrel.com/tools/webfont-generator">this</a> link.
Select OPTIMAL and upload your file. Unzip the files generated by the tool.</p>
<p><strong>Step 3: </strong> Now you need open the file that ends with '.css', a simple text editor such as notepad will do just fine.</p>
<p><strong>Step 4: </strong> Find the font-family property(see image below)</p><br />
<asp:Image ID="imgFontCssEx" runat="server" ImageUrl="~/Images/fontCssImg.png" /><br />
<p><strong>Step 5: </strong> Make sure you copy the font-family value exactly as shown in the css into the text box below, marked Font Name.</p>
<asp:TextBox ID="txtFontFam" runat="server"></asp:TextBox>
<asp:Label ID="lblFontFam" runat="server" Text="Font Family"></asp:Label>
<br />
<p><strong>Step 6: </strong> Enter a display name for your font.</p>
<asp:TextBox ID="txtFontName" runat="server"></asp:TextBox>
<asp:Label ID="lblFontName" runat="server" Text="Display Name" ></asp:Label>
<br />
<p><strong>Step 7: </strong> Now you need to upload the files specified below:</p><br />
<asp:FileUpload ID="flupFonts" runat="server" AllowMultiple="true" />
<asp:Label ID="lblCss" runat="server" AssociatedControlID="flupFonts" Text="Upload file with files ending: .css, .ttf, .svg, .eot, .woff, .woff2"></asp:Label>
<p><strong>Finally:&nbsp</strong> Click the button below and the font will be made available.</p>
<br />
<asp:Button ID="btnUploadFont" runat="server" Text="Add Font" OnClick="btnUploadFont_Click" />
</div>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Admin_addFont : System.Web.UI.Page
{
private string fontUploadDirectory;
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define parameters
cmd.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
cmd.Parameters["#status"].Value = "Display";
// attempt to connect to db, read data, fill dataset and bind gridview. Catch exceptions and close the connection.
try
{
con.Open();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
grdFonts.DataSource = ds;
grdFonts.DataBind();
}
catch (Exception err)
{
lblFontGrd.Text = err.Message;
}
finally
{
con.Close();
}
}
protected void grdFonts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdFonts.PageIndex = e.NewPageIndex;
BindGrid();
}
public static string[] BuildFont(string font)
{
string[] array = new string[1];
array[0] = font;
return array;
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { "eot", "ttf", "svg", "woff", "woff2", "css" };
bool isValidFile = false;
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
if (fileCollection.Count == 6)
{
string serverFileName = Path.GetFileName(flupFonts.PostedFile.FileName);
string ext = Path.GetExtension(serverFileName).ToLower();
string fullUploadPath = Path.Combine(fontUploadDirectory, serverFileName);
try {
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
for (int i = 0; i < validFileTypes.Length; i++)
{
if (ext == "." + validFileTypes[i])
{
isValidFile = true;
if (!File.Exists(fullUploadPath))
{
try
{
flupFonts.PostedFile.SaveAs(fullUploadPath);
break;
}
catch (Exception err)
{
lblUpload.Text = err.Message;
}
}
}
}
if (!isValidFile)
{
lblUpload.Text += "Invalid File. Please upload a File with extension " + string.Join(",", validFileTypes);
}
}
fontDbInfo();
BindGrid();
}
catch (Exception err)
{
lblUpload.Text = "Error: " + err.Message;
}
}
else
{
if (fileCollection.Count < 6)
{
lblUpload.Text = "Please make sure you select all required files.";
}
if (fileCollection.Count > 6)
{
lblUpload.Text = "You have selected too many files. Please only add the required files.";
}
}
}
}
protected void fontDbInfo()
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_Fonts", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Add";
cmd.Parameters.Add(new SqlParameter("#FontName", SqlDbType.VarChar, 50));
cmd.Parameters["#FontName"].Value = txtFontName.Text;
cmd.Parameters.Add(new SqlParameter("#FontFamily", SqlDbType.VarChar, 50));
cmd.Parameters["#FontFamily"].Value = txtFontFam.Text;
cmd.Parameters.Add(new SqlParameter("#Discontinued", SqlDbType.Bit));
cmd.Parameters["#Discontinued"].Value = 0;
// try to open database, insert font info, catch errors and close the connection
try
{
con.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Fonts");
}
catch (Exception err)
{
lblFontGrd.Text = "Error: " + err.Message;
}
finally
{
con.Close();
}
}}
my stored procedure:
CREATE PROCEDURE [ProductDetails].[bnc_Fonts]
-- Add the parameters for the stored procedure here
#Status varchar(50) = '',
#FontId tinyint = '',
#FontName varchar(50) = '',
#FontFamily varchar(50) = '',
#Discontinued bit = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if (#Status = 'Display')
begin
select FontId, FontName, FontFamily, Discontinued
from ProductDetails.Fonts
where Discontinued = 0
order by FontName asc
end
if (#Status = 'FontFam')
begin
select FontFamily from ProductDetails.Fonts
where FontId = #FontId
end
if (#Status = 'Add')
begin
insert into ProductDetails.Fonts (FontName, FontFamily, Discontinued)
values (#FontName, #FontFamily, #Discontinued)
end
if (#Status = 'Delete')
begin
UPDATE ProductDetails.Fonts
SET Discontinued = #Discontinued
where FontId = #FontId
end
END
I think the way you are attempting to loop through the HttpPostedFile collection is causing you problems. Try checking file validity in a separate method. I'd also suggest you break this problem down into pieces you can test. For example, try a simple Test page with code something like this. Hope this helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Data;
public partial class Test : System.Web.UI.Page
{
private string fontUploadDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure files are uploaded to the right folder
fontUploadDirectory = Server.MapPath(#"~\fonts\");
}
protected void btnUploadFont_Click(object sender, EventArgs e)
{
string[] validFileTypes = { ".eot", ".ttf", ".svg", ".woff", ".woff2", ".css" };
// check files are being submitted
if (flupFonts.HasFiles == false)
{
lblUpload.Text = "No files have been selected.";
}
else
{
HttpFileCollection fileCollection = Request.Files;
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
string ext = System.IO.Path.GetExtension(uploadedFont.FileName);
if (isValid(uploadedFont, validFileTypes, ext))
{
uploadedFont.SaveAs(fontUploadDirectory + "\\" + System.IO.Path.GetFileName(uploadedFont.FileName));
}
}
}
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext)
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
}
Replace this loop:
foreach (HttpPostedFile uploadedFont in flupFonts.PostedFiles)
{
...
}
With this:
foreach(string key in flupFonts.Keys)
{
HttpPostedFile uploadedFont = flupFonts[key];
...
}

ScriptManager not updating

Evening all I'm trying to create a page that will pull locations from a database and display it within a a gridview, this gridview then dictates some points that appear on a Google maps element. It works fine on start up but when I use the text box to refine the items in gridview the map disappears. I'm guessing it's an issue with my ScriptManager but I'm unsure exactly what the cause is. Any ideas would be greatly appreciated. Apologies for the wall of code I'm just a bit unsure what might be relevant at this stage.
<%# Page Title="" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MapTest.Default" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
function RefreshUpdatePanel() {
__doPostBack('<%= txtSearch.ClientID %>', '');
};
</script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA5U97yznzCvzDaUZjT3AydlQqyFBQVYc8&sensor=false">
</script>
<link href="App_Themes/Default/default.css" rel="stylesheet" type="text/css" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="Wrapper">
<asp:ScriptManager ID="MasterScriptManger" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upanSearch" runat="server" UpdateMode="Conditional" OnPreRender="upanSearch_PreRender">
<ContentTemplate>
<div class="DataTable">
<span>Search</span>
<asp:TextBox ID="txtSearch" runat="server" onkeyup="RefreshUpdatePanel();" onfocus="this.value = this.value;" OnTextChanged="txtSearch_TextChanged" AutoPostBack="True" AutoCompleteType="Disabled"></asp:TextBox>
<asp:GridView ID="grdLocations" runat="server" AutoGenerateColumns="False" DataSourceID="sqldsLocations">
<AlternatingRowStyle BackColor="#F6F6F6" />
<Columns>
<asp:BoundField DataField="Location Name" HeaderText="Location Name" SortExpression="Location Name" />
<asp:BoundField DataField="Latitude" HeaderText="Latitude" SortExpression="Latitude" />
<asp:BoundField DataField="Longitude" HeaderText="Longitude" SortExpression="Longitude" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsLocations" runat="server" ConnectionString="<%$ ConnectionStrings:MapTestGuestConn %>" SelectCommand="GetLocations(mySearch)" CancelSelectOnNullParameter="False" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="txtSearch" Name="mySearch" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
</div>
<div id="googleMap" style="width:500px;height:380px;"></div>
<script type="text/javascript">
initializeMap();
</script>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged"/>
</Triggers>
</asp:UpdatePanel>
</div>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
namespace MapTest
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "Default";
}
protected void upanSearch_PreRender(object sender, EventArgs e)
{
//MessageBox.Show(BuildMapScript());
ScriptManager.RegisterClientScriptBlock(upanSearch, upanSearch.GetType(), "BuildMap", BuildMapScript(), false);
//ScriptManager.RegisterStartupScript(upanSearch, upanSearch.GetType(), "BuildMap", BuildMapScript(), false);
}
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
txtSearch.Focus();
}
protected string BuildMapScript()
{
grdLocations.DataBind();
string markers = GetMarkers();
string myScript = #"
<script type='text/javascript'>
function initializeMap() {
var mapOptions = {
center: new google.maps.LatLng(50.826108, -1.075011),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById('googleMap'),
mapOptions);"
+ markers +
#"}
</script>";
return myScript;
}
protected string GetMarkers()
{
string markers = "";
int c = 1;
foreach (GridViewRow grdRow in grdLocations.Rows)
{
markers +=
#"var marker" + c + #" = new google.maps.Marker({
position: new google.maps.LatLng(" + grdRow.Cells[1].Text.ToString() + ", " +
grdRow.Cells[2].Text.ToString() + ")," +
#"map: myMap,
title:'" + grdRow.Cells[0].Text.ToString() + "'});";
c++;
}
return markers;
}
}
}
The updatepanel updating would cause the issue you experience. You would need to reinitialize the google map on postback if within the updatepanel... to do that you can attach to Sys.Application's endRequest event, which fires when the updatepanel finishes, and reinitialize the map. Or pull the map out of the updatepanel.

Ajax rating tool in Gridview

Hi I have a problem with my code, I am implementing a rating application. I have connected a access database to my website. I then added in the ajax control and gridview etc..
this is my code so far..
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<asp:GridView ID="gvwMake" runat="server" DataKeyNames="MachineID"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" AllowPaging="True"
OnSelectedIndexChanged="gvwMake_SelectedIndexChanged">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
<Columns>
<asp:BoundField DataField="Make" HeaderText="Make" />
<asp:ImageField DataImageUrlField="Image"></asp:ImageField>
<asp:TemplateField HeaderText="Machine Rating">
<ItemTemplate>
<cc1:Rating ID="Rating1"
AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar"
EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar"
CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
That all seems to be working fine however the problem is with the code behind.
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
public partial class rate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = MachineClass.getMachine();
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
}
protected void gvwMake_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwMake.PageIndex = e.NewPageIndex;
DataSet ds = MachineClass.getMachine();
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
protected void gvwMake_SelectedIndexChanged(object sender, EventArgs e)
{
string strID = gvwMake.SelectedRow.Cells[2].Text;
Session["TID"] = strID;
Response.Redirect("~/Result.aspx");
}
protected void btnSearch_Click(object sender, EventArgs e)
{
DataSet ds = MachineClass.getMachine(txtSearch.Text);
gvwMake.DataSource = ds.Tables["dtMachine"];
gvwMake.DataBind();
}
private void ShowData()
{
using (OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT TOP 20 Products.ProductID, Products.ProductName," +
" Products.UnitPrice, Products.SupplierID, " +
"Products.CustomerRating FROM Products",
new OleDbConnection(
ConfigurationManager.ConnectionStrings["comac.mdb.accdb"].ToString())))
{
DataTable dt = new DataTable();
da.SelectCommand.Connection.Open();
da.Fill(dt);
this.gvwMake.DataSource = dt;
this.gvwMake.DataBind();
}
}
protected void Rating1_Changed(object sender,
AjaxControlToolkit.RatingEventArgs e)
{
AjaxControlToolkit.Rating myRating =
(AjaxControlToolkit.Rating)sender;
System.Text.RegularExpressions.Regex rexLineNo =
new System.Text.RegularExpressions.Regex("ctl\\d+");
this.updateRating(this.MachineId(
rexLineNo.Match(myRating.UniqueID).ToString()), e.Value);
}
private string MachineId(string LineNo)
{
foreach (GridViewRow r in this.gvwMake.Rows)
{
Label lblMachineId = (Label)r.FindControl("lblMachineId");
if (lblMachineId.UniqueID.Contains(LineNo))
{
return lblMachineId.Text;
}
}
return string.Empty;
}
private void updateRating(string MachineId, string Rating)
{
OleDbParameter paramRating = new OleDbParameter("#Rating", Rating);
OleDbParameter paramMachineId =
new OleDbParameter("#MachineId", MachineId);
using (OleDbCommand cmd = new OleDbCommand(
"UPDATE Machines SET CustomerRating " +
"= #Rating WHERE Machines.MachineID=#MachineId",
new OleDbConnection(
ConfigurationManager.ConnectionStrings["comac.mdb.accdb"].ToString())))
{
cmd.Parameters.Add(paramRating);
cmd.Parameters.Add(paramMachineId);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
This is my first time using the ajax rating control and not sure if the codes suitable for it when i run the webpage i get an error message
'ASP.rate_aspx' does not contain a definition for 'OnRatingChanged' and no extension method 'OnRatingChanged' accepting a first argument of type 'ASP.rate_aspx' could be found (are you missing a using directive or an assembly reference?)
What I could see from the below part of your code:
<ItemTemplate>
<cc1:Rating ID="Rating1"
AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar"
EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar"
CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>
is the place where you use the Rating Control, you are assigning OnChanged Event to a Code behind method OnRatingChanged (mentioned as OnChanged="OnRatingChanged"in your code) and since your code behind does not have any method named OnRatingChanged the error is thrown saying 'ASP.rate_aspx' does not contain a definition for 'OnRatingChanged'.
So if you are really not using this event then remove the event (remove the part: OnChanged="OnRatingChanged" from your code) or in case if you are using this then include an appropriate 'OnRatingChanged' method in your code behind.
Okay here is the C# code. You will have to import the following namespaces:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using AjaxControlToolkit;
//the page_onload add the following code
if (!IsPostBack)
{
gvFruits.DataSource = GetData("SELECT FruitId, FruitName, ISNULL((SELECT AVG(Rating) FROM Fruit_Ratings WHERE FruitId = Fruits.FruitId), 0) Rating FROM Fruits");
gvFruits.DataBind();
}
private static DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
//and here is the code full functioning app for rating.[Full functioning rating app code][1]
[1]: http://www.aspsnippets.com/Articles/Using-ASPNet-AJAX-Rating-Control-inside-GridView-TemplateField-ItemTemplate.aspx
Okay Try the demo from this website probably you will find it usefull>
http://www.aspsnippets.com/Articles/Using-ASPNet-AJAX-Rating-Control-inside-GridView-TemplateField-ItemTemplate.aspx
first add ajax toolkit from your ajax toolbox and then apply followin coding with css.
<style type="text/css">
.Star
{
background-image: url(Images/rsz_star-deselect.png);
height: 17px;
width: 17px;
}
.WaitingStar
{
/*background-image: url(images/WaitingStar.gif);*/
height: 17px;
width: 17px;
}
.FilledStar
{
background-image: url(Images/rsz_star-select.png);
height: 17px;
width: 17px;
}
</style>
<ItemTemplate>
<cc1:Rating ID="Rating1" AutoPostBack="true" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar" CurrentRating='<%# Eval("Rating") %>'>
</cc1:Rating>
</ItemTemplate>

Using jQuery UI Themes with ASP.Net Controls

I am considering the feasibility of using jQuery UI themes to my ASP.NET website.
I found following issues. How do we correct them?
Internet Explorer (IE 8) --> The gridline is not visible at the bottom
(when there is no multiple pages)
Mozilla --> Gridline is not available for header
Chrome --> Working fine
Is it compatible with asp.net controls?
Can you please direct me to some examples that shows correct use of these jQuery classes with asp.net controls (without side effects)?
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.6/jquery-ui.js"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/themes/sunny/jquery-ui.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" PageSize="4">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" ReadOnly="true"
SortExpression="ProductName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="Qty" ReadOnly="true" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="CategoryName" HeaderText="Category" ReadOnly="true" SortExpression="CategoryName" />
</Columns>
</asp:GridView>
</div>
<br />
</form>
</body>
</html>
--Code Behind
using System;
using System.Web.UI.WebControls;
using System.Data;
public partial class MyGridTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("ProductName"), new DataColumn("QuantityPerUnit"), new DataColumn("CategoryName") });
dt.Rows.Add("Shirt", 200);
dt.Rows.Add("Football", 30);
dt.Rows.Add("Bat", 22.5);
//dt.Rows.Add("Football", 30);
//dt.Rows.Add("Bat", 22.5);
//dt.Rows.Add("Football", 30);
//dt.Rows.Add("Bat", 22.5);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
GridView1.CssClass = "ui-widget-content";
if (GridView1.Rows.Count > 0)
{
//To render header in accessible format
GridView1.UseAccessibleHeader = true;
//Add the <thead> element
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
GridView1.HeaderRow.CssClass = "ui-widget-header";
//Add the <tfoot> element
GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
if (GridView1.TopPagerRow != null)
{
GridView1.TopPagerRow.TableSection = TableRowSection.TableHeader;
}
if (GridView1.BottomPagerRow != null)
{
GridView1.BottomPagerRow.TableSection = TableRowSection.TableFooter;
}
}
}
}
Just out of interest. What happens on when you add this meta tag.
<meta http-equiv="x-ua-compatible" content="IE=8" />

Categories