I am trying to create and run a sqldependency method from a web form class, where I have a "UpdateMethod", which I implemented using a window-form as reference.
However the web-form version of the method, does not update the page-load automatically on the client-side, when there is a change in the database, whereas window-form does.
Window form method version:
delegate void GridDelegate(DataTable table);
private void UpdateGrid()
{
string sql = "SELECT * FROM [dbo].[User]";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionstring))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
dep = new SqlDependency(cmd); //Passing Command to SQL dependency
dep.OnChange += dep_OnChange;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
}
}
}
dataGridView1.Invoke((GridDelegate)delegate(DataTable table)
{ dataGridView1.DataSource = table; }, dt);
}
Web form version of the method:
private void UpdateGrid()
{
string sql = "SELECT * FROM [dbo].[User] order by uploadDate desc";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
try
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
con.Open();
SqlDependency dep;
dep = new SqlDependency(cmd); //Passing Command to SQL dependency
dep.OnChange += dep_OnChange;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
// GridView1.DataSource = rdr;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
I tried adding in a try..Catch statement in the web form version, but I am getting no errors from it. Please advice, in how I can test this method further, in order to resolve this issue. Any hints/advice would be most appreciated. Thank you
This is a mockup. I do not have a sql server to work with; hence I've done my example with timers (threading). I have used SignalR for the purpose. Make sure the browser is also a bit modern (IE10 +, Chrome, Mozilla, etc which supports websockets).
Create your hub class with a constructor
The constructor initializes and fires the timer thread. The thread executes code which instructs the hub to call a particular js method on the client(s) (i.e. all those browsers that are connected to the hub).
This particular js method will host the logic to refresh our gridview which is inside an updatepanel.
Write the necessary javascript to do the refresh (aspx)
The aspx page is a simple in design. It has an updatepanel inside which you have a gridview bound to a sqldatasource, and a linkbutton whose main responsibility is to refresh the grid data (server-side). The code for this is very simple, and will be shown below later. You can notice that for the refresh to work we are simulating a manual click on the LinkButton control (hosted inside udpatepanel).
write necessary logic to connect with the hub (aspx)
This is code which connects to the hub, and writes the js method which should be called when you receive the server message.
Also make sure you have the owin startup class files added to the project. Refer SignalR tutorials for more signalr stuff.
DataHub.cs
using Microsoft.AspNet.SignalR;
using System.Threading;
using System.Diagnostics;
namespace WebApp.SignalR.GridUpdatePanel
{
public class DataHub : Hub
{
public DataHub()
{
Debug.Print("Ctor executed...");
Timer tmr = new Timer(new TimerCallback(this.RefreshThread), null, 1000, 5000);
}
//Method which invokes the client js code...
public void Refresh()
{
Clients.All.refreshData();
}
public void RefreshThread(object obj)
{
Debug.Print("RefreshThread Called...");
Refresh();
}
}
}
SignalRPage.aspx
<%# Page Title="SignalR Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SingalRPage.aspx.cs" Inherits="WebApp.SignalR.GridUpdatePanel.SingalRPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphPageHeadScripts" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphPageBody" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:BoundField DataField="PName" HeaderText="PName" SortExpression="PName" />
<asp:BoundField DataField="PAge" HeaderText="PAge" SortExpression="PAge" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:PersonsDbConnectionString1 %>" DeleteCommand="DELETE FROM [Persons] WHERE [Id] = #Id" InsertCommand="INSERT INTO [Persons] ([Id], [PName], [PAge]) VALUES (#Id, #PName, #PAge)" ProviderName="<%$ ConnectionStrings:PersonsDbConnectionString1.ProviderName %>" SelectCommand="SELECT [Id], [PName], [PAge] FROM [Persons]" UpdateCommand="UPDATE [Persons] SET [PName] = #PName, [PAge] = #PAge WHERE [Id] = #Id">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Id" Type="Int32" />
<asp:Parameter Name="PName" Type="String" />
<asp:Parameter Name="PAge" Type="Int32" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="PName" Type="String" />
<asp:Parameter Name="PAge" Type="Int32" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<br />
<asp:LinkButton ID="LinkButton1" runat="server" CssClass="btn btn-default" OnClick="LinkButton1_Click">Refresh</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphPageBottomScripts" runat="server">
<script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
<script src="signalr/hubs"></script>
<script>
function refreshGrid() {
console.log('grid refresh');
var lnk = document.getElementById('<%= LinkButton1.ClientID %>');
lnk.click();
}
</script>
<script>
$(function () {
var chat = $.connection.dataHub;
chat.client.refreshData = function () {
refreshGrid();
};
$.connection.hub.start().done(function () {
console.log('hub started...');
});
});
</script>
</asp:Content>
Here I have used the following master page.
Site.Master
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="WebApp.SignalR.GridUpdatePanel.Site" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="/Content/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<asp:ContentPlaceHolder ID="cphPageHeadScripts" runat="server"></asp:ContentPlaceHolder>
</head>
<body>
<form runat="server">
<asp:ContentPlaceHolder ID="cphPageBody" runat="server"></asp:ContentPlaceHolder>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="/Scripts/jquery-1.9.1.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/Scripts/bootstrap.min.js"></script>
<asp:ContentPlaceHolder ID="cphPageBottomScripts" runat="server"></asp:ContentPlaceHolder>
</body>
</html>
Finally the code-behind of the main aspx page will look as follows:
using System;
using System.Diagnostics;
namespace WebApp.SignalR.GridUpdatePanel
{
public partial class SingalRPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Debug.Print("LinkButton1_Click");
Label1.Text = DateTime.Now.ToLongTimeString();
GridView1.DataBind();
}
}
}
Related
I'm following this example and I'm having some hard time displaying data in a gridview. When the page is loaded it gets to GetData and returns values.
If in the immediate windows after I fill datatable and see the count ?dtResult.Rows.Count I get 1001. So I know I have data.
However, when the I debug the app I just get the three buttons. What am I missing here?
Here's the aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="TestApp.test" %>
<%# Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<!DOCTYPE html>
<html lang="en-us">
<head id="Head1" runat="server">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/redmond/jquery-ui.css" />
<!-- The jQuery UI theme extension jqGrid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />
<!-- jQuery runtime minified -->
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-2.0.3.min.js" type="text/javascript"></script>
<!-- The localization file we need, English in this case -->
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
<!-- The jqGrid client-side javascript -->
<script src="/js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<style type="text/css">
body, html { font-size: 80%; }
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="message">
<script type="text/javascript">
function addRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
grid.editGridRow("new", grid.addDialogOptions);
}
function editRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
var editOptions = grid.getGridParam('editDialogOptions');
if (rowKey) {
grid.editGridRow(rowKey, editOptions);
}
else {
alert("No rows are selected");
}
}
function delRow() {
var grid = jQuery("#<%= JQGrid1.ClientID %>");
var rowKey = grid.getGridParam("selrow");
if (rowKey) {
grid.delGridRow(rowKey, grid.delDialogOptions);
}
else {
alert("No rows are selected");
}
}
</script>
<input type="button" onclick="addRow()" value="Add" />
<input type="button" onclick="editRow()" value="Edit" />
<input type="button" onclick="delRow()" value="Delete" />
<trirand:jqgrid runat="server" ID="JQGrid1"
OnRowDeleting="JQGrid1_RowDeleting"
OnRowAdding="JQGrid1_RowAdding"
OnRowEditing="JQGrid1_RowEditing">
<Columns>
<trirand:JQGridColumn DataField="Addressbookid" Editable="false" PrimaryKey="true" />
<trirand:JQGridColumn DataField="ClientName" Editable="true" />
<trirand:JQGridColumn DataField="Clientno" Editable="true" />
<trirand:JQGridColumn DataField="IndustryName" Editable="true" />
</Columns>
<ToolBarSettings ShowEditButton="true" ShowAddButton="true" ShowDeleteButton="true" />
<EditDialogSettings CloseAfterEditing="true" Caption="The Edit Dialog" />
<AddDialogSettings CloseAfterAdding="true" />
</trirand:jqgrid>
</div>
<br /><br />
</div>
</form>
Here's the codebehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestApp
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
JQGrid1.DataSource = GetData();
JQGrid1.DataBind();
}
protected DataTable GetData()
{
if (Session["EditDialogData"] == null)
{
// Create a new Sql Connection and set connection string accordingly
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = ConfigurationManager.ConnectionStrings["Sandbox"].ConnectionString;
sqlConnection.Open();
string sqlStatement = "Select * from voiceportal.dbo.clients_v";
// Create a SqlDataAdapter to get the results as DataTable
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlStatement, sqlConnection);
// Create a new DataTable
DataTable dtResult = new DataTable();
// Fill the DataTable with the result of the SQL statement
sqlDataAdapter.Fill(dtResult);
Session["EditDialogData"] = dtResult;
return dtResult;
}
else
{
return Session["EditDialogData"] as DataTable;
}
}
}
}
Any suggestions on how I can fix this?
Thanks
My two cents.
Make sure that the grid locale js file is in the right place and served well to your browser. See the related line:
<script src="/js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>
Open up your developer console with F12, refresh the page and look for the downloaded files and error messages on the console which can tell if this doesn't go well.
Double check that the data you serve matches the column configuration. Pay special attention to camel casing. .NET properties start with uppercase, they are camel cased, but JSON data often starts with lowercase. That also depends on if you use any transformations (like NewtonSoft and stuff). I don't know what's in your voiceportal.dbo.clients_v table, please specify your schema. In your ASPX code Addressbookid and Clientno are not camel cased. Shouldn't they be AddressbookId and ClientNo? Depends on your schema and what actually comes through the wire.
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.
I have a very simple ASP.NET page that uploads an Excel workbook, then processes it. It uses AJAXFILEUPLOAD from the AJAX toolkit on ASP.NET... Here's the markup:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="ImportWorkbook.aspx.cs" Inherits="Timesheet.ImportWorkbook" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="HeaderContentPlaceHolder">
<h1 class="topContent">
Upload CPAS Timesheet Workbooks
</h1>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="RightContentPlaceHolder" runat="server">
<br />
<br />
<asp:HiddenField ID="tbTSID" runat="server" />
<asp:HiddenField ID="tbWorkbookPath" runat="server" />
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server" AllowedFileTypes="xls,xlsx,xlsm"
CssClass="dropdown" MaximumNumberOfFiles="1" OnUploadComplete="AjaxFileUpload1_UploadComplete" />
<br />
<br />
<asp:Panel ID="ProcessChoices" runat="server" >
<br />
<br />
<p>
Select how you want this workbook processed:</p>
<br />
<asp:RadioButtonList ID="rbChoices" runat="server" BorderStyle="Groove" BorderWidth="2px"
BorderColor="Black" BackColor="Teal" Font-Names="Tahoma" Font-Size="10pt" ForeColor="White"
Width="40%">
<asp:ListItem Value="True" Selected="True">  Replace ALL Items in the Timesheet</asp:ListItem>
<asp:ListItem Value="False">  Add Items from this Workbook to the Existing Timesheet Items</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
<asp:Button ID="btnValidate" runat="server" Text="Validate and Process"
BackColor="#B92217" ForeColor="White" BorderColor="#7C1810"
BorderStyle="Groove" Font-Names="Tahoma" onclick="btnValidate_Click" />
</asp:Panel>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="BottomSpanContentPlaceHolder" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</asp:Content>
The master page and css pages are trivial, formatting only.
Here's the codebehind:
using System;
using System.IO;
using TimesheetUtilites;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
namespace Timesheet
{
public partial class ImportWorkbook : System.Web.UI.Page
{
private const string HDriveLocation= "H:\\mtv\\secure\\Construction\\Access\\CPAS WorkArea\\TimesheetUploads\\";
private string strWorkbookPath;
private int currTSID;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["ID"] != null)
{
tbTSID.Value = Request.QueryString["ID"]; // Storing the Timesheet ID in a hidden Textbox
}
}
else
{
if (!string.IsNullOrEmpty(tbWorkbookPath.Value))
{
ProcessChoices.Enabled = true;
}
}
int.TryParse(tbTSID.Value, out currTSID);
strWorkbookPath = tbWorkbookPath.Value;
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxFileUploadEventArgs e)
{
strWorkbookPath = HDriveLocation + Path.GetFileName(e.FileName);
tbWorkbookPath.Value = strWorkbookPath;
AjaxFileUpload1.SaveAs(strWorkbookPath);
ProcessChoices.Enabled = true;
}
protected void btnValidate_Click(object sender, EventArgs e)
{
bool processOption;
bool.TryParse(rbChoices.SelectedValue, out processOption);
strWorkbookPath = tbWorkbookPath.Value;
TimesheetUtilites.ImportTimesheet imp = new ImportTimesheet(currTSID, strWorkbookPath, processOption);
}
}
}
My issue is simple. Although the event handler "AjaxFileUpload1_UploadComplete" works fine, and uploads the file in an instant, when I fire the "btnValidate_Click" event, the "tbWorkbookPath.Value" has become an empty string, and the "ProcessChoices.Enabled" propety doesn't change. Needless to say, the "Upload Complete" event handler is the only opportunity I have to capture this file path, so I'm at a loss what I'm doing wrong.
I posted on ASP.NET and go NO answers. Can anyone give me an idea where to start?
This is information you should be storing in your page's ViewState so that it persists between postbacks and resets on page initialization. Change your private string member to something like the following:
private string strWorkbookPath {
get {
return this.ViewState["strWorkbookPath"];
}
set {
this.ViewState["strWorkbookPath"] = value;
}
}
If you need a primer on what the ViewState is, check out this article on MSDN: Saving Web Forms Page Values Using View State. It's a bit dated but still communicates the basics of how ViewState operates currently.
Put a hidden field with runat="server" attribute on your page and use the below script:
<script type="text/javascript">
function uploadComplete(sender, args) {
var filename = args.get_fileName();
$("#hiddden_field_id").val(filename);
}
</script>
Now you should be getting the image name in your events.
I think you should try storing that value in session rather than a hidden field as the page is not reloaded and it was an ajax call. So when the button is clicked for validation, it is actually another request made but the value of the hidden field in this page object and the hidden field is still empty. Once your job is done for that value in session, remove it from there or set it to some different value.
I am new to ASP>NET(C#). But I am using Winform before.
In my Project I have two dropdown list. if i change the one,.. the second will change auto.
But even event also not firing in ASP.net. Without event how to i manage that?.
<div id="Div1" class="ui-content ui-body-a" runat="server">
<asp:dropdownlist id="ddlOutlet" runat="server" autopostback="True" onselectedindexchanged="ddlOutlet_SelectedIndexChanged"
ontextchanged="ddlOutlet_TextChanged">
</asp:dropdownlist>
<br />
<asp:dropdownlist id="ddlServedAt" runat="server">
</asp:dropdownlist>
<br />
<asp:button id="btnLogin" runat="server" text="LogIn" />
</div>
C#
I already Added items in both dropdown list in page load event. But When I change the ddlOutlet selected index changed Event not firing. So I tried to TextChanged Events Also. But nothing happened. What is problem?.
Page Load Event -
protected void Page_Load(object sender, EventArgs e)
{
HelpingFunctions hp = new HelpingFunctions();
string id = Request.QueryString["id"];
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "SELECT c.Outlet_Master_Name,d.Fbserved_Served FROM mcs_user a, mcs_user_outlet b,outlet_master c,fb_served d WHERE a.Mcs_User_Id='" + id + "' and"
+ " a.Mcs_User_Id = b.Mcs_User_Outlet_User_Id and c.Outlet_Master_Id = b.Mcs_User_Outlet_Outlet_Id and c.Outlet_Master_Id=d.Fbserved_outletid";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlOutlet.Items.Add(Reader[0].ToString());
ddlServedAt.Items.Add(Reader[1].ToString());
}
connection.Close();
}
Selected Item -
protected void ddlOutlet_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlServedAt.SelectedItem.Value = Reader[0].ToString();
}
connection.Close();
}
I read some same issue problem solutions, but they told to set AutoPostBack="True". I checked that also.
I don't know why ASP.net hard to Event firing also?.
UPDATED QUESTION
In my Project,.. I am using jquerymobile(http://jquerymobile.com/) with ASP.Net and mysql.
I have two drop down list controls and ONE button.
But When I change the ddlOutlet selected index changed Event not firing. After the button Click the Events Are fired Correctly. But Before that They not fire. I do't know Why its happen.
I Give my Complete Code Below.
My Complete ASPX File :-
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="OutLet.aspx.cs" Inherits="MobileApp.OutLet" %>
<!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>
<meta name="viewport" content="width=device-width; height=device-height; initial-scale=1.0; maximum-scale=1.5; user-scalable=no;" />
<link href="Styles/jquery.mobile-1.0b3.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.mobile-1.0b3.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server" data-ajax="false">
<div id="mainheader" class="ui-header-fixed ui-bar-a">
</div>
<div id="Div1" class="ui-content ui-body-a" runat="server">
<%-- <asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>--%>
<asp:DropDownList ID="ddlOutlet" runat="server"
AutoPostBack="True" onselectedindexchanged="ddlOutlet_SelectedIndexChanged"
ontextchanged="ddlOutlet_TextChanged">
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlServedAt" runat="server" AutoPostBack="True">
</asp:DropDownList>
<br />
<asp:Button ID="btnLogin" runat="server" Text="LogIn"
onclick="btnLogin_Click" />
<%-- </ContentTemplate>
</asp:UpdatePanel> --%>
</div>
</form>
</body>
</html>
my Code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
namespace MobileApp
{
public partial class OutLet : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HelpingFunctions hp = new HelpingFunctions();
string id = Request.QueryString["id"];
if (!Page.IsPostBack)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "SELECT c.Outlet_Master_Name,d.Fbserved_Served FROM mcs_user a, mcs_user_outlet b,outlet_master c,fb_served d WHERE a.Mcs_User_Id='" + id + "' and"
+ " a.Mcs_User_Id = b.Mcs_User_Outlet_User_Id and c.Outlet_Master_Id = b.Mcs_User_Outlet_Outlet_Id and c.Outlet_Master_Id=d.Fbserved_outletid";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlOutlet.Items.Add(Reader[0].ToString());
ddlServedAt.Items.Add(Reader[1].ToString());
}
connection.Close();
}
}
protected void ddlOutlet_SelectedIndexChanged(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
ddlServedAt.SelectedValue = Reader[0].ToString();
}
connection.Close();
}
protected void ddlOutlet_TextChanged(object sender, EventArgs e)
{
//MySqlConnection connection = new MySqlConnection("server=192.168.1.100;username=mcubic;password=mcs#2011$;database=mcubic;");
//string query = "select Fbserved_Served from fb_served where Fbserved_outletid = (select Outlet_Master_Id from outlet_master where Outlet_Master_Name ='" + ddlOutlet.SelectedItem.ToString() + "')";
//MySqlCommand command = new MySqlCommand(query, connection);
//connection.Open();
//MySqlDataReader Reader = command.ExecuteReader();
//while (Reader.Read())
//{
// ddlServedAt.SelectedItem.Value = Reader[0].ToString();
//}
//connection.Close();
}
protected void btnLogin_Click(object sender, EventArgs e)
{
}
}
}
Create the drop down list(the one that changes the content of the other one)
Activity: <asp:DropDownList ID="cmbActivity" runat="server" OnSelectedIndexChanged="cmbActivity_SelectedIndexChanged" AutoPostBack="true" />
Then in your C#, your load event should be like this
if (Session["staffId"] == null)
{
Response.Redirect("~/login.aspx");
}
else
{
if (!IsPostBack)
{
cmbActivity.DataSource = a;
cmbActivity.DataTextField = "activityName";
cmbActivity.DataValueField = "activiyId";
}
}
Your selectedIndex_Changed method still remains the same. This should work. Have more than one item in the list to be sure.
I hope this helps
try by Adding Page.IsPostBack in your page_Load event...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//your page load code.....
}
}
EDIT - 1
Sample Code of ASPX page in Web Application
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList id="id1" runat="server" AutoPostBack="true"
onselectedindexchanged="id1_SelectedIndexChanged">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="id2" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
Sample code of code behind in Web Application
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 WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void id1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Sample code of ASPX page in Website
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs" Inherits="Default4" %>
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList id="id1" runat="server" AutoPostBack="true"
onselectedindexchanged="id1_SelectedIndexChanged">
<asp:ListItem Text="1" Value="1"></asp:ListItem>
<asp:ListItem Text="2" Value="2"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList id="id2" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
Sample code of Code behind in Website
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default4 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void id1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
OP already had this in his question, but I was missing autopostback="True"
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" />