ASP.NET DevExpress Gridview update operation - c#

net devexpress controls. First i tried to implement this edit command on gridview. Everything seems fine but only one problem i got is when i tried to click edit link a popup forms comes out in which i can not type inside the box. Finally, when i click on "Update" button an error comes out says "Object reference not set to an instance of an object." Please help me out this situation where did i make mistake. Thanking you.
<%# Register assembly="DevExpress.Web.v17.1, Version=17.1.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" namespace="DevExpress.Web" tagprefix="dx" %>
<asp:Content runat="server" ID="BodyContent1" ContentPlaceHolderID="ContentPlaceHolder1">
<dx:ASPxGridView ID="GridView1" runat="server" ClientInstanceName="GridView1"
KeyFieldName="TestConfigId" AutoGenerateColumns="False" Width="850px"
OnRowUpdating="Gridview1_RowUpdating" >
<Columns>
<dx:GridViewDataTextColumn Caption="TestConfigId" FieldName="TestConfigId" Name="TestConfigId" Visible="true" VisibleIndex="0">
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Main Test" FieldName="MainTest" Name="MainTest" Settings-AllowSort="False" VisibleIndex="1" >
</dx:GridViewDataTextColumn>
<dx:GridViewDataTextColumn Caption="Sub Test" FieldName="SubTest" Name="SubTest" Settings-AllowSort="False" VisibleIndex="2" >
</dx:GridViewDataTextColumn>
<dx:GridViewCommandColumn ShowEditButton="true" VisibleIndex="3" Width="100" FixedStyle="Left">
</dx:GridViewCommandColumn>
</Columns>
<Settings HorizontalScrollBarMode="Visible"/>
<SettingsBehavior AutoExpandAllGroups="true"/>
<SettingsBehavior AllowFocusedRow="True"/>
<SettingsResizing ColumnResizeMode="NextColumn"/>
<Styles>
<FixedColumn BackColor="LightYellow"></FixedColumn>
</Styles>
<Settings ShowStatusBar="Visible" />
<SettingsEditing Mode="PopupEditForm" />
</dx:ASPxGridView>
<dx:ASPxPopupControl ID="popupSample" runat="server" ShowCloseButton="true" ShowHeader="true"
PopupHorizontalAlign="WindowCenter" PopupVerticalAlign="WindowCenter">
</dx:ASPxPopupControl>
</asp:Content>
Code Behind file
protected void Gridview1_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "update_test_configuration";
cmd.Parameters.Add("#TestConfigId", SqlDbType.Int).Value = Convert.ToInt32(e.NewValues["TestConfigId"]);
cmd.Parameters.Add("#MainTest", SqlDbType.NVarChar).Value = e.NewValues["MainTest"].ToString();
cmd.Parameters.Add("#SubTest", SqlDbType.NVarChar).Value = e.NewValues["SubTest"].ToString();
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
}
Stored Procedure
CREATE PROCEDURE [dbo].[update_test_configuration]
#TestConfigId int = 0,
#MainTest nvarchar(100),
#SubTest nvarchar(100)
AS
BEGIN
SET NOCOUNT ON;
UPDATE dbo.TestConfigMaster
SET MainTest = #MainTest,
SubTest =#SubTest
WHERE TestConfigId = #TestConfigId
END

If e.NewValues["MainTest"] is null, then e.NewValues["MainTest"].ToString() will generate an error because you cannot call ToString() on a null reference. i.e., you cannot say "null.ToString()."
Same will apply the rest of the fields, i.e. TestConfigId and SubTest.
Maybe you could try this way:
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter { SqlDbType = System.Data.SqlDbType.NVarChar, ParameterName = "#MainTest", Value = $"{ e.NewValues["MainTest"] }" });
etc.

Related

GridView Remove one definition

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.

How to display 2 numbers after decimal in Web Page grid view in ASPX Web Forms?

This is the table I have created:
CREATE TABLE Product
(ID INTEGER IDENTITY(1,1) NOT NULL ,
Product_No AS RIGHT ('PDT0000' + CAST(ID AS VARCHAR(10)),10) PERSISTED PRIMARY KEY CLUSTERED,
Product_Image VARBINARY (MAX) NOT NULL,
Product_Name VARCHAR(50) NOT NULL,
Product_Category_No INTEGER NOT NULL FOREIGN KEY REFERENCES Product_Category(Product_Category_No),
Product_Price MONEY NOT NULL,
Product_Quantity INTEGER NOT NULL,
Grocery_Branch_No INTEGER NOT NULL FOREIGN KEY REFERENCES Grocery_Branch(Grocery_Branch_No)
)
When I insert a value like 10.50 or 100.45 or 11.05 in Product_Price column and then run SELECT * FROM Product in both SQL Server and Visual Studio, the Product_Price column value gets displayed as 10.50 or 100.45 or 11.05.
However, when I see the result of SELECT * FROM Product in a gridview from aspx page, then it shows 10.5000 or 100.4500 or 11.0500.
In other words, the results for Product_Price column value in SQL Server and Visual Studio is showing 2 numbers after the decimal (because in INSERT Statement I have added 2 numbers after decimal).
But, while running the aspx page, in the Product_Price column value in Grid View, it is showing 4 numbers after the decimal.
I made sure to add the Regular Expression Validator for Product_Price column in AddProducts.aspx
p>
Price:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="TextBox2" ErrorMessage="This field is required"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator7" runat="server" ControlToValidate="TextBox2" ErrorMessage="After decimal only 2 numbers" ValidationExpression="^\d{1,9}\.\d{1,2}$"></asp:RegularExpressionValidator>
</p>
Then this is what I have done in my AddProducts.cs
Stream stream = postedfile.InputStream;
BinaryReader binaryreader = new BinaryReader(stream);
byte[] bytes = binaryreader.ReadBytes((int)stream.Length);
string branch = Session["BranchAdmin"].ToString();
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("AddProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.Parameters.AddWithValue("#ProductImage", FileUpload1.FileBytes);
cmd.Parameters.AddWithValue("#ProductName", TextBox1.Text);
cmd.Parameters.AddWithValue("#ProductCategoryName", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("#ProductPrice", TextBox2.Text);
cmd.Parameters.AddWithValue("#ProductQuantity", TextBox3.Text);
cmd.Parameters.AddWithValue("#GroceryBranchName", branch);
cmd.ExecuteNonQuery();
con.Close();
MessageBox("New Product has been added");
Then this is what I have done in ViewProducts.aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="100px" Width="150px"
ImageUrl='<%#"data:Image/png/jpg/jpeg/gif/bmp;base64," + Convert.ToBase64String((byte[])Eval("Product_Image")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Product_Name" HeaderText="Product" />
<asp:BoundField DataField="Product_Category_Name" HeaderText="Category" />
<asp:BoundField DataField="Product_Price" HeaderText="Price" DataFormatString="{0} AUD" />
<asp:BoundField DataField="Product_Quantity" HeaderText="Quantity" />
<asp:BoundField DataField="Grocery_Branch_Name" HeaderText="Branch" />
</Columns>
</asp:GridView>
And this is what I have done in ViewProducts.cs
private void DisplayProducts()
{
string CS;
CS = "data source=LAPTOP-ODS96MIK\\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("ViewProducts", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
I still could not figure out why the ViewProducts.aspx page is showing 4 numbers after the decimal for Product_Price column value in Grid View.
It would be helpful if the recommended syntax solution is provided to display 2 numbers after the decimal for Product_Price column value in Grid View.
This code should work:
<asp:BoundField DataField="Product_Price" HeaderText="Price" DataFormatString="{0:0.00} AUD" />

Displaying Data from SQL Server database in an ASP.NET table

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"));
}

Updating Database with sessions not working C# SQL

So my code brings across the searched for userID of a lecturer and the ModuleID previously selected by the user. However it breaks on this line;
myCommand.ExecuteNonQuery();
The error is;
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '('.
I don't know why it does it but I can see that my stuff is being pulled across when I use a break point.
Front end code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT Lecturer_Records.UserID, Lecturer_Records.FirstName, Lecturer_Records.Surname, Lecturer_Records.PhoneNumber, Users.Email
FROM Lecturer_Records
INNER JOIN Users ON Lecturer_Records.UserID = Users.UserID
WHERE (Users.Email = #email)">
<SelectParameters>
<asp:QueryStringParameter Name="email" QueryStringField="searchlects" />
<asp:SessionParameter Name="ModuleID" SessionField="ModuleID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="SearchResult" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="SearchResult_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
And my C# code
protected void SearchResult_SelectedIndexChanged(object sender, EventArgs e)
{
// open new connection
SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
connection1.Open();
string SearchUser = SearchResult.SelectedRow.Cells[1].Text;
string Module = (string)Session["ModuleID"];
SqlCommand myCommand = new SqlCommand("UPDATE [Modules] SET (UserID = '" + SearchUser + "') WHERE (ModuleID = '" + Module + "')", connection1);
myCommand.ExecuteNonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
You don't need any ( or ) in your command. They breaks your sql syntax. Just delete them.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Based on your column names, they seems as a numerical types. That means, you might need to delete single quotes as well. If you use prepared statements, you will not need this of course.
And use using statement to dispose your connection and command.
using(var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using(var myCommand = connection1.CreateCommand())
{
myCommand.CommandText = #"UPDATE Modules SET UserID = #userid
WHERE ModuleID = #moduleid";
myCommand.Parameters.Add("#userid", SqlDbType.NVarChar).Value = SearchUser;
myCommand.Parameters.Add("#moduleid", SqlDbType.NVarChar).Value = Module;
// I assumed your column types are nvarchar
connection1.Open();
myCommand.ExecutenonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
But really, those columns are seem as numerical types. Either you can their type or change their name that points their types as character.

Problems using UpdateProgress

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.

Categories

Resources