From searching the internet for a short time I was able to write this code for an internal application I will be developing using Visual Studio ASP.NET / C#.
I am calling the database and creating a connection and then building a dropdown selection from the SQL code used.
Being very new to C# I am struggling to bring other fields into my table (e.g. Text strings and numbers and not just having a drop down field.
Ideally I'd like to show data like:
Activity | Hazards | Controls | RiskLevel(Dropdown)|
Here is my front end code:
<asp:Table ID="Table1" runat="server" Font-Size="Medium" Width="960" BorderWidth="3" CellPadding="5" CellSpacing="5" CssClass="table table-bordered table-striped table-hover table-condensed table-responsive">
<asp:TableHeaderRow runat="server" Font-Bold="true">
<asp:TableHeaderCell ID="ActivityID" Width="20%">Activity</asp:TableHeaderCell>
<asp:TableHeaderCell ID="HazardsID">Hazards</asp:TableHeaderCell>
<asp:TableHeaderCell ID="RiskID" Width="15%">Risk Level</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow ID="TableRow1" runat="server" >
<asp:TableCell><asp:Label ID="lblActivity" runat="server" Text="Label"></asp:Label></asp:TableCell>
<asp:TableCell><asp:Label ID="lblHazards" runat="server" Text="Label"></asp:Label></asp:TableCell>
<asp:TableCell><asp:DropDownList ID="ddl1" runat="server"></asp:DropDownList></asp:TableCell>
</asp:TableRow>
<asp:TableFooterRow runat="server" >
<asp:TableCell ColumnSpan="3" HorizontalAlign="Right" Font-Italic="true">
INSERT **TEXTBOX FOR OTHER INFORMATION ATTACHED HERE!**
</asp:TableCell>
</asp:TableFooterRow>
</asp:Table>
Here is my current back end code:
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd =
new SqlCommand("SELECT TOP 1000 [MainActivityID],[ID],[Activity],[Hazards],CASE WHEN [Risk_Level] LIKE 'H' THEN 'HIGH' WHEN [Risk_Level] LIKE 'M' THEN 'MEDIUM' WHEN [Risk_Level] LIKE 'L' THEN 'LOW' WHEN[Risk_Level] LIKE 'T' THEN 'TRIVIAL' WHEN[Risk_Level] LIKE 'N' THEN 'N/A' END AS[Risk_Level],[Controls] FROM [STRIDES_SQL].[dbo].[STRIDES_RA_Activities]"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ddl1.DataSource = cmd.ExecuteReader();
ddl1.DataTextField = "Risk_Level";
ddl1.DataValueField = "MainActivityID";
ddl1.DataBind();
String input = lblActivity.Text;
con.Close();
}
}
ddl1.Items.Insert(0, new ListItem("--Select Risk Level--", "0"));
}
Related
I'm trying to create a web page with the aps.net framework and I connect to the SQL server successfully and I want to display the data from the database in the Grid View and there are a search box and dropdown list but there is an error when I try to search
this is the error message:
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
and my code viewpage1.aspx
the GridView
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Format="dd/MM/yyyy" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="InvoiceID" DataSourceID="SqlDataSource3">
<AlternatingRowStyle BackColor="#CCCCCC" />
-and this the sqldatasource
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:connStr %>" SelectCommand="Select * from [Portal].[fn_GetInvoices] (#SearchText) where CompanyCode=#CompanyCode and InvoiceDate between #fromDate and #toDate">
<SelectParameters>
viewpage1.aspx.cs
sqlcomm.CommandText = sqlquery;
sqlcomm.Connection = sqlconn;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcomm);
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
This is a common error message.
I OFTEN use the wizards to build a gridview I use this:
From above, I choose create new data source.
I let the wizard run.
BUT THEN we wind up with some MESSAY sqldatasource in the web page. I do NOT like them, and they NEAR ALWAYS just cause you pain.
So, what I will then do this:
Remove the sqldata source from the web markup - you don't' need that mess anyway.
eg this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CSharpWebApp.Properties.Settings.TEST4 %>"
SelectCommand="SELECT [ID], [Fighter], [Engine], [Thrust], [Description], [ImagePath]
FROM [Fighters]"></asp:SqlDataSource>
DELETE the above!!!!
Now WHEN you WILL use code to load up the Gridview? Then you ALSO must turn off (remove) the fact that you NOT GOING to use the sql data source anymore.
So in your GV, remove this:
So, all that error message is telling you is you are trying to set the data source in "code" but you ALREADY have a sql datasource setup in the markup.
So, get in the habit of blowing out and removing the sqldata source on the page, and ALSO remove the GV data source setting in the markup.
So, now say I will have this GV, and NOT have ANY data source in the markup in the web page. (and I recommend you do this). So, I still VERY often use the wizards. Even for a dropdown list, a gridview, repeaters, and even listview (my favorite).
So, run wizards - build the markup
Then blow out (remove) the SqlDataSource, and the
DataSourceID="SqlDataSource1" from the control (in this case gv).
So, as noted, you cannot have BOTH a DataSourceID="SqlDataSource1" and THEN try to use code. It is one or the other - and that's what the error message is telling you.
So, now we have this markup:
(and the wizards generated most of this for me!!!)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
OnClientClick ="popimage(this);return false"
ImageUrl = '<%# Eval("ImagePath") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Just nice clean markup - no Sqldatasource junk.
Now we are free to write normal code like a normal human, and we can fill the grid like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters", conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And our results are now this:
Ok, so now lets add a search box above the GV to search the GV.
Say you can type in the first few chars of the Fighter jet name, and we want to filter by that:
So, drop in a text box above the GV, + search button.
We now have say this:
<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
style="margin-left:15px" CssClass="btn"
/>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
So, now the page with searching looks like this:
Say we search for Lockheed - but even just typing in Lock would be fine.
thus:
And now our code can say be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid("");
}
void LoadGrid(string MySearch)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
if (MySearch != "")
{
cmdSQL.CommandText += #" WHERE Fighter LIKE #Fighter + '%'";
cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
}
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
protected void cmdSearch_Click(object sender, EventArgs e)
{
LoadGrid(txtSearch.Text);
}
}
So, I am STRONG suggesting that you DUMP the sqldata source on the web page markup. Such Sqldata soruces on the page can be great for one time load or data display. But the VERY instant you want control, filters, and need to use code?
Quite much the SAME instant it is time to drop and toss out and remove the data source from the web markup. You be glad you did, and as you can see, you now have 100% EASY AND SIMPLE control of the data you shove into the GV, and that includes endless possible use of simple code and buttons to add filters etc. to that data.
I have what I think is a simple question, however it might be more complex..
I have spent a few days looking for the answer on google and various questions on this site but cannot seem to come right.
What I am trying to do is to bind to a Gridview on the User Control ascx page from the Default.aspx.cs on the Page Load event.
User Control markup is as follows:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="VulnerabilityExternalIP.ascx.cs" Inherits="VulnerabilityAssesment.Controls.VulnerabilityExternalIP" %>
<asp:Table runat="server" CellPadding="1" CellSpacing="2">
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityName" runat="server" Text="Vulnerability Name:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityNameText" runat="server" Text='<%# Eval("MainVulnerabilityName") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityCategory" runat="server" Text="Category:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityCategoryText" runat="server" Text='<%# Eval("Category") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityPopularity" runat="server" Text="Popularity:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityPopularityText" runat="server" Text='<%# Eval("Popularity") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:Label ID="lblVulnerabilityRisk" runat="server" Text="Risk:" CssClass="itemName"></asp:Label>
</asp:TableCell>
<asp:TableCell>
<asp:Label ID="blVulnerabilityRiskText" runat="server" Text='<%# Eval("RiskFactor") %>'></asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<br />
<asp:Label ID="lblHostsAffected" runat="server" Text="Hosts Affected:" CssClass="itemName"></asp:Label>
<br />
<asp:TextBox ID="txtHostsAffected" runat="server" TextMode="MultiLine" Width="700px" ReadOnly="true" BroderWidth="0px" Text='<%# Eval("HostNamePort") %>'></asp:TextBox>
<asp:GridView ID="gvHostsAffected" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True">
</asp:GridView>
I am referencing the User Control on the Default.aspx as follows:
<%# Register Src="~/Controls/VulnerabilityExternalIP.ascx" TagName="VulnerabilityExternalIP" TagPrefix="uc1" %>
Within the default.asxp I have the following defined:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:ListView ID="lvVulnerabilityExternalIP" runat="server">
<ItemTemplate>
<uc1:VulnerabilityExternalIP Template="<%# Container.DataItem %>" runat="server" ID="vulnerabilityExtIP" name="vulnext" />
</ItemTemplate>
</asp:ListView>
</asp:Content>
The code behind on Default.aspx.cs is as follows:
namespace VulnerabilityAssesment
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string HostNamePort = "";
string VulnerabilityDesc = "";
string VulnerabilitySummary = "";
string VulnerabilitySolution = "";
string VulnerabilityCVE = "";
string VulnerbilityLink = "";
// Use connection string from Web.Config
string connection = ConfigurationManager.ConnectionStrings["csVulnerabilityAssesment"].ConnectionString;
//Create new SQL Connection
SqlConnection conn = new SqlConnection(connection);
//Create Stored Procedure Command and Declare Parameters
SqlCommand vulnerabilityHeader = new SqlCommand("[dbo].[_spGet_VulnerabilityHeader]", conn);
vulnerabilityHeader.CommandType = CommandType.StoredProcedure;
vulnerabilityHeader.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
//Create Data Adapter and Data Set
SqlDataAdapter sdaVulnerabilityHeader = new SqlDataAdapter(vulnerabilityHeader);
DataSet dsVulnerabilityHeader = new DataSet();
//Open Connection
conn.Open();
//Fill Data Adapter
sdaVulnerabilityHeader.Fill(dsVulnerabilityHeader);
//Fill in template
List<VulnerabilityTemplate> Template = new List<VulnerabilityTemplate>();
if (dsVulnerabilityHeader.Tables != null)
if (dsVulnerabilityHeader.Tables[0].Rows.Count == 0)
{
}
else
if (dsVulnerabilityHeader.Tables.Count > 0)
{
foreach (DataRow dr in dsVulnerabilityHeader.Tables[0].Rows)
{
string GroupID = dr["GroupSequence"].ToString();
//Declare Stored Procedue for Vulnerability Details and set Parameters
SqlCommand vulnerabilityDetail = new SqlCommand("[dbo].[_spGet_VulnerabilityDetail]", conn);
vulnerabilityDetail.CommandType = CommandType.StoredProcedure;
vulnerabilityDetail.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
vulnerabilityDetail.Parameters.Add("#GroupSequence", SqlDbType.VarChar).Value = GroupID;
// Declare SQL Data Adapter for Vulnerability Detail
SqlDataAdapter sdaVulnerabilityDetail = new SqlDataAdapter(vulnerabilityDetail);
DataSet dsVulnerabilityDetail = new DataSet();
// Fill Data Adapter
sdaVulnerabilityDetail.Fill(dsVulnerabilityDetail);
// Declare Stored Procedure for Vulnerability Summary and Set Paramters
SqlCommand vulnerabilitySummary = new SqlCommand("[dbo].[_spGet_VulnerabilitySummary]", conn);
vulnerabilitySummary.CommandType = CommandType.StoredProcedure;
vulnerabilitySummary.Parameters.Add("#VulnerabilityReport", SqlDbType.VarChar).Value = "External IP Ranges";
vulnerabilitySummary.Parameters.Add("#GroupSequence", SqlDbType.VarChar).Value = GroupID;
// Declare SQL Data Adapter for Vulnerability Detail
SqlDataAdapter sdaVulnerabilitySummary = new SqlDataAdapter(vulnerabilitySummary);
DataSet dsVulnerabilitySummary = new DataSet();
// Fill Data Adapter
sdaVulnerabilityDetail.Fill(dsVulnerabilityDetail);
sdaVulnerabilitySummary.Fill(dsVulnerabilitySummary);
foreach (DataRow row in dsVulnerabilityDetail.Tables[0].Rows)
{
if (HostNamePort != "")
HostNamePort += Environment.NewLine;
HostNamePort += row["HostnamePort"].ToString();
}
foreach (DataRow vulnerabilitySummaryRow in dsVulnerabilitySummary.Tables[0].Rows)
{
VulnerabilityDesc += vulnerabilitySummaryRow["VulnerabilityDesc"].ToString();
VulnerabilitySummary += vulnerabilitySummaryRow["VulnerabilitySummary"].ToString();
VulnerabilitySolution += vulnerabilitySummaryRow["VulnerabilitySolution"].ToString();
}
//myGrid.DataSource = dsVulnerabilityDetail.Tables[0];
//GridView myGrid = (GridView)lvVulnerabilityExternalIP.Items.FindControl("gvHostsAffected");
// Always returns null :(
GridView myGrid = (GridView)lvVulnerabilityExternalIP.FindControl("gvHostsAffected");
Template.Add(new VulnerabilityTemplate
{
MainVulnerabilityName = dr["MainVulnerabilityName"].ToString(),
Category = dr["Category"].ToString(),
Popularity = dr["Popularity"].ToString(),
Riskfactor = dr["RiskFactor"].ToString(),
HostNamePort = HostNamePort
//VulnerabilityDesc = VulnerabilityDesc,
//VulnerabilitySolution = VulnerabilitySolution,
//VulnerabilitySummary = VulnerabilitySummary
}
);
myGrid.DataBind();
}
}
lvVulnerabilityExternalIP.DataSource = Template;
lvVulnerabilityExternalIP.DataBind();
conn.Close();
}
// Below Does not work
protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DataTable table = (DataTable)e.Item.DataItem;
GridView myGrid = (GridView)e.Item.FindControl("gvHostsAffected");
myGrid.DataSource = table;
myGrid.DataBind();
}
}
}
}
I cannot seem to find the gvHostsAffected grid view to bind it to the dsVulnerabilityDetail.Tables[0] value (which should be a single column called HostsAffected, this result could return 1 or more rows.
I have included two things that I have tried denoted by the comment //Below does not work.
The Template.Add method does work and it populates necessary information on the user control.
Is there any way I can find the Gridview control during the iteration and populate it with the results from the dsVulnerabilityDetail data set?
Thank you in advance.
Update 10 April 2017
Below is the Code Behind for the WebControl, I see I forgot to include it in the original Question.
namespace VulnerabilityAssesment.Controls
{
public partial class VulnerabilityExternalIP : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public GridView myGridView
{
get
{
return gvHostsAffected;
}
set
{
gvHostsAffected = value;
}
}
}
}
The markup for Web Control include the answer by VDWWD.
First, add a public GridView property to the User Control
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public GridView myGridView
{
get
{
return GridView1;
}
set
{
GridView1 = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Then you can access it like yo would a GridView on the same page. The only thing left to do is to use FindControl to find the User Control inside the ListView
protected void Button1_Click(object sender, EventArgs e)
{
WebUserControl1 control = lvVulnerabilityExternalIP.Items[2].FindControl("vulnerabilityExtIP") as WebUserControl1;
control.myGridView.DataSource = mySource;
control.myGridView.DataBind();
}
I want change the listview data with checkboxlist items. But when checked 2 or multiply items write this error:
The variable name '#TId' has already been declared.
or
Index was outside the bounds of the array.
Please help me. :(
HTML:
<asp:ListView ID="ltvProduct" runat="server">
<ItemTemplate>
<asp:HyperLink runat="server" ID="hypProduct" NavigateUrl='<%#"show.aspx?NId="+Eval("MId") %>'>
<div class="col-lg-4 Border Text PContainer ">
<asp:Image runat="server" ImageUrl='<%#"/img/Gallery/"+Eval("PicUrl") %>' CssClass="padding-product" Width="240px" /><br />
<asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>' CssClass="EnName"></asp:Label><br />
</div>
</asp:HyperLink>
</ItemTemplate>
</asp:ListView>
CHECKBOX BIND CODE:
SqlConnection conT = new SqlConnection(ConfigurationManager.ConnectionStrings["CSTR"].ConnectionString);
SqlCommand cmT = new SqlCommand("Select * from Type", conT);
SqlDataAdapter adpT = new SqlDataAdapter(cmT);
DataTable dtT = new DataTable();
adpT.Fill(dtT);
chkType.DataSource = dtT;
chkType.DataTextField = "Name";
chkType.DataValueField = "TId";
chkType.DataBind();
SELECTEDINDEXCHANGE:
string strconnectionP = ConfigurationManager.ConnectionStrings["CSTR"].ConnectionString;
SqlConnection objconnectionP = new SqlConnection(strconnectionP);
string strsqlP = "select * from Model where TId=#TId";
SqlCommand objcommandP = new SqlCommand(strsqlP, objconnectionP);
for (int i = 0; i < chkType.Items.Count; i++)
{
if (chkType.Items[i].Selected)
{
objcommandP.Parameters.AddWithValue("#TId", chkType.SelectedValue[i]);
objconnectionP.Open();
ltvProduct.DataSource = objcommandP.ExecuteReader();
ltvProduct.DataBind();
}
objconnectionP.Close();
}
}
In your SELECTEDINDEXCHANGE event you are executing your SqlCommand inside a loop for multiple times. If you want to use a SqlCommand multiple times you should clear your parameter everytime after executing SqlCommand. Use this line of code
objcommandP.Parameters.Clear();
Ater these lines
ltvProduct.DataSource = objcommandP.ExecuteReader();
ltvProduct.DataBind();
I am working on a small search form that has two text fields: One that allows users to search for a job list (which is basically a wish list--don't know why they want to call it a "job list" but whatever) by entering in part of or a full email address or someone's first and/or last name (This textbox is called SearchName). This field is required and if it is blank when the user hits "Search," an error message appears telling them so. The second textbox is optional, and it allows users to enter in a city or a state to help narrow their search down even more (this textbox is called SearchLocation).
I have a function (called getJobLists()) that is used by the search button to get results.
As it is right now, the part of the function that returns results based on what is entered into the SearchName field works perfectly. However, I cannot get any results for SearchLocation. When I enter a valid email or name into SearchName, then enter a valid city or state into SearchLocation, I get no results. However, if I enter in anything invalid (i.e. a city that is not associated with the entered email or name) the "no results found" message does appear.
I have tested both SQL queries in my search function in SQL Server Management Studio and they do work perfectly.
I have a try-catch inside the search function, but no error is being shown, not even in the console.
This is the code behind:
protected void Page_Load(object sender, System.EventArgs e)
{
// CHECK IF THE WISHLIST SEARCH ENABLED
StoreSettingsManager settings = AbleContext.Current.Store.Settings;
if (!settings.WishlistSearchEnabled)
{
Response.Redirect(AbleCommerce.Code.NavigationHelper.GetHomeUrl());
return;
}
}
protected void getJobLists()
{
try
{
if (SearchName.Text != "")
{//if SearchName.Text is not blank
if (SearchLocation.Text != "")
{//check to see if SearchLocation.Text is not blank either
string sqlSelect = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%') AND ((City + Province) LIKE '%'+#Location+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.Parameters.AddWithValue("#Location", String.Format("%{0}%", SearchLocation.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl = ds.Tables.Add("jobsListsTbl");
jobsListsTbl.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl.NewRow();
dr["User"] = reader["Name"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl";
WishlistGrid.DataBind();
}
}//end of if(SearchLocation.Text !='')
else
{//if SearchLocation.Text is blank, then go with this code instead
string sqlSelect2 = "SELECT (FirstName +' '+ LastName) AS 'FullName', UserName, (Address1 + ', ' +City + ', ' + Province) AS 'Address' FROM ac_Users INNER JOIN ac_Wishlists ON ac_Wishlists.UserId = ac_Users.UserId INNER JOIN ac_Addresses ON ac_Addresses.UserId = ac_Wishlists.UserId WHERE IsBilling ='true' AND (UserName LIKE '%'+#UserName+'%' OR (FirstName + LastName) LIKE '%'+#UserName+'%')";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
SqlCommand cmd = new SqlCommand(sqlSelect2, cn);
cmd.Parameters.AddWithValue("#UserName", String.Format("%{0}%", SearchName.Text));
cmd.CommandType = CommandType.Text;
cn.Open();
DataSet ds = new DataSet();
DataTable jobsListsTbl2 = ds.Tables.Add("jobsListsTbl2");
jobsListsTbl2.Columns.Add("User", Type.GetType("System.String"));
jobsListsTbl2.Columns.Add("PrimaryAddress", Type.GetType("System.String"));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = jobsListsTbl2.NewRow();
dr["User"] = reader["UserName"];
dr["PrimaryAddress"] = reader["Address"];
jobsListsTbl2.Rows.Add(dr);
}
}
WishlistGrid.DataSource = ds;
WishlistGrid.DataMember = "jobsListsTbl2";
WishlistGrid.DataBind();
}
}//end if SearchLocation.Text is empty
}//end of if SearchName.Text !==''
}
catch (Exception x)
{
errors5.Text += "ERROR: " + x.Message.ToString() + "<br />";
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
WishlistGrid.Visible = true;
getJobLists();
}
And this is the designer code for the search form (Note: the NavigateUrl is not set for the hyperlink yet. I will set it once everything is displaying properly for the search results):
<div id="findWishlistPage" class="mainContentWrapper">
<div class="section">
<div class="introDiv">
<div class="pageHeader">
<h1>Find a Job List</h1>
</div>
<div class="content">
<asp:label id="errors" runat="server" text=""></asp:label>
<asp:label id="errors2" runat="server" text=""></asp:label>
<asp:label id="errors3" runat="server" text=""></asp:label>
<asp:label id="errors4" runat="server" text=""></asp:label>
<asp:label id="errors5" runat="server" text=""></asp:label>
<asp:UpdatePanel ID="Searchajax" runat="server">
<ContentTemplate>
<asp:Panel ID="SearchPanel" runat="server" EnableViewState="false" DefaultButton="SearchButton">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" EnableViewState="false" />
<table class="inputForm">
<tr>
<th class="rowHeader">
<asp:Label ID="SearchNameLabel" runat="server" Text="Name or E-mail:" AssociatedControlID="SearchName" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:Textbox id="SearchName" runat="server" onfocus="this.select()" Width="200px" EnableViewState="false"></asp:Textbox>
<asp:RequiredFieldValidator ID="SearchNameValdiator" runat="server" ControlToValidate="SearchName"
Text="*" ErrorMessage="Name or email address is required." EnableViewState="false"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<th class="rowHeader">
<asp:Label ID="SearchLocationLabel" runat="server" Text="City or State (optional):" EnableViewState="false"></asp:Label>
</th>
<td>
<asp:TextBox id="SearchLocation" runat="server" onfocus="this.select()" Width="140px" EnableViewState="false"></asp:TextBox>
<asp:LinkButton ID="SearchButton" runat="server" CssClass="button linkButton" Text="Search" OnClick="SearchButton_Click" EnableViewState="false" />
</td>
</tr>
</table><br />
<asp:GridView ID="WishlistGrid" runat="server" AllowPaging="True"
AutoGenerateColumns="False" ShowHeader="true"
SkinID="PagedList" Visible="false" EnableViewState="false">
<Columns>
<asp:TemplateField HeaderText="Name">
<HeaderStyle CssClass="wishlistName" />
<ItemStyle CssClass="wishlistName" />
<ItemTemplate>
<asp:HyperLink ID="WishlistLink" runat="server" >
<%#Eval("User")%>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<HeaderStyle CssClass="wishlistLocation" />
<ItemStyle CssClass="wishlistLocation" />
<ItemTemplate>
<asp:Label ID="Location" runat="server" Text='<%#Eval("PrimaryAddress")%>'></asp:Label>
<%--'<%#GetLocation(Eval("User.PrimaryAddress"))%>'--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<asp:Localize ID="EmptySearchResult" runat="server" Text="There were no job lists matching your search criteria."></asp:Localize>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</div>
Can anyone please tell me what I'm missing or doing wrong?
Okay, I finally solved the issue. Apparently, it was a variable naming issue I kept overlooking. But now it all works okay! :)
I have a button on my ASP.NET page, which fetches some data from my database and displays it on a gridview.
This process takes a while, so I thought I'll add an updateprogress AJAX control. Now when I click the button, the updateprogress image shows up and data is being fetched from my database successfully (I checked this from some logs that I have in my DB). But there are 2 issues:
(1) The updateprogress image shows only for about 2 minutes. But my buttonclick event takes about 5 minutes to complete. Basically the updateprogress stops showing up even before my task is complete, which defeats its purpose.
(2) GridView doesn't show up. It shows up correctly if I don't use scriptmanager/AJAX.
Any ideas?
Some relevant code snippets:
<div style="position: absolute; top: 300px; left: 19px; width: 568px; height: 48px;">
<table>
<tr>
<td>
<asp:Button ID="btnGenerateReport" runat="server" Height="37px" Text="Generate Report"
Width="132px" onclick="btnGenerateReport_Click" />
</td>
<td class="style5">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="Panel">
<ContentTemplate>
<asp:UpdateProgress ID="PageUpdateProgress" runat="server">
<ProgressTemplate>
<img runat="server" src="updateprogress.gif"
style="position: static; width: 32px;"> </img></ProgressTemplate>
</asp:UpdateProgress>
<div style="position: absolute; top: 423px; left: 9px; width: 795px; height: 984px;">
<asp:GridView ID="Report" runat="server"
AllowSorting="True" AutoGenerateColumns="False"
Height="622px" BorderStyle="Solid"
Width="779px" PageSize="100" HorizontalAlign="Center">
<Columns>
<asp:BoundField HeaderText="AccountId" DataField="AccountId">
<ControlStyle BorderStyle="Solid" Width="20px" />
</asp:BoundField>
<asp:BoundField HeaderText="User Name" ReadOnly="True" DataField="UserName">
<ControlStyle Width="50px" />
</asp:BoundField>
<asp:BoundField HeaderText="C2" ReadOnly="True"
DataField="C2">
<ControlStyle BorderStyle="Solid" Width="20px" />
</asp:BoundField>
<asp:BoundField HeaderText="C1" ReadOnly="True"
DataField="C1">
<ControlStyle BorderStyle="Solid" Width="20px" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnGenerateReport" EventName="click" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
<asp:Button ID="btnExportToExcel" runat="server" Text="Export To Excel"
Height="37px" Width="132px" onclick="btnExportToExcel_Click" />
</td>
</tr>
</table>
</div>
Codefile part:
protected void btnGenerateReport_Click(object sender, EventArgs e)
{
FetchAccounts();
long startId = FetchAuditData();
AggregateAuditData(startId);
dsAnalysisReport = GenerateDataSet();
if (dsAnalysisReport == null || dsAnalysisReport.Tables.Count == 0)
lblErrorText.Text = "No Data Found for the input information";
else
BindData(dsAnalysisReport);
}
public void FetchAccounts()
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
sqlConnection.Open();
cmdstring = #"[spo_FetchAccounts]";
cmd = new SqlCommand(cmdstring, sqlConnection) { CommandType = CommandType.StoredProcedure };
cmd.CommandTimeout = 100000;
cmd.Parameters.Add("#MaxActivationDate", SqlDbType.DateTime);
cmd.Parameters["#MaxActivationDate"].Value =
DateTime.Parse(txtStartDate.Text) - new TimeSpan(1, 0, 0, 0);
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
}
public long FetchAuditData()
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
sqlConnection.Open();
cmdstring = #"[spo_GetComparisonData]";
cmd = new SqlCommand(cmdstring, sqlConnection) { CommandType = CommandType.StoredProcedure };
cmd.CommandTimeout = 100000;
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime);
cmd.Parameters["#StartDate"].Value = txtStartDate.Text;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime);
cmd.Parameters["#EndDate"].Value = txtEndDate.Text;
SqlParameter returnValue = new SqlParameter("#Return_Value", SqlDbType.BigInt);
returnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValue);
cmd.ExecuteNonQuery();
long startId = long.Parse(cmd.Parameters["#Return_Value"].Value.ToString());
sqlConnection.Close();
return startId;
}
}
private void AggregateAuditData(long startId)
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
sqlConnection.Open();
cmdstring = #"[spo_ComparisonTable]";
cmd = new SqlCommand(cmdstring, sqlConnection) { CommandType = CommandType.StoredProcedure };
cmd.CommandTimeout = 100000;
cmd.Parameters.Add("#StartId", SqlDbType.Int);
cmd.Parameters["#StartId"].Value = startId;
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
}
public DataSet GenerateDataSet()
{
using (var sqlConnection = new SqlConnection(ConnectionString))
{
sqlConnection.Open();
cmdstring = #"SELECT * FROM XAccounts";
cmd = new SqlCommand(cmdstring, sqlConnection);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
sqlConnection.Close();
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
return ds;
return null;
}
}
private void BindData(DataSet ds)
{
BindReportGrid(Report, ds.Tables[0]);
}
private void BindReportGrid(GridView gridToBind, DataTable dataTableToBind)
{
gridToBind.DataSource = dataTableToBind;
gridToBind.DataBind();
}
As per issue (1) most likely it is ajax timing out. Default timeout is 90 seconds. To increase that use ScriptManager's AsyncPostBackTimeout property:
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="400">
</asp:ScriptManager>
If ajax call is timing out, controls on the page might not work correctly so increasing timeout might solve problem (2) as well.
I have had very same problems with ASP.NET UpdateProgress. I fixed it by handling script manager events directly:
<script language="javascript" type="text/javascript">
//adding event handlers for ajax initialize request and end request
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(ShowHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(HideHandler);
function ShowHandler(sender, args) {
//show div with animation
pcProcessing_ClientInstance.Show();
}
function HideHandler(sender, args) {
//hide div with animation
pcProcessing_ClientInstance.Hide();
}
</script>
Maybe you want this: http://www.codeproject.com/kb/Ajax/ModalUpdateProgress.aspx
It works well for me, even with lengthy operations.
Seems like your grid is outside the Update panel, if you are using a update panel and you button is inside the update panel and grid is outside the update panel in that case everything will happen at server side but you will not find any changes in the UI.
Try to place your grid inside the update panel.
Move the UpdateProgress outside of the UpdatePanel.