DataGrid Example – Part 1

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 1 Comment on DataGrid Example – Part 1

For the basics of DataGrid please refer this post: https://jitendrazaa.com/blog/?p=188

In this example, i will explain the basics of DataGrid control like Theming, Databinding etc.

We will start our example with creating the SQL Express database of Employee which will contain the following fields : Id, FName, LName, Email.

Now create a stored procedure to insert the data into Table.

CREATE PROCEDURE dbo.AddEmployee
@FName varchar(50),
@LName varchar(50),
@Email varchar(50)
AS
INSERT INTO Employee (FName,LName,Email) values (@FName,@LName,@Email)

In ASPX page, write the code to input the Employee information.

First Name : <asp:TextBox ID="txtFName" runat="server"/><br />
Last Name :<asp:TextBox ID="txtLName" runat="server"/><br />
Email :<asp:TextBox ID="txtEmail"; runat="server"/><br />
<asp:Button ID="btnSubmit" Text="Add Record" runat="server" OnClick="btnSubmit_Click"/>

Go to the property of Employee.mdf and select connection string as shown in below image.

On the click event of the button write below function:

string conString = @"Data Source=.SQLEXPRESS;AttachDbFilename=""|DataDirectory|Employee.mdf"";Integrated Security=True;User Instance=True";
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = null;
SqlCommand cmd = null;
try {
con = new SqlConnection(conString);
     con.Open();
     cmd = new SqlCommand("AddEmployee", con);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@FName", txtFName.Text);
     cmd.Parameters.AddWithValue("@LName", txtLName.Text);
     cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
     cmd.ExecuteNonQuery();
     showConfirmationMessage();
}
catch (CustomException ex) {
ex.logException();
}finally{
    con.Close();
}
}
 private void showConfirmationMessage()
{
      ClientScriptManager csMngr = Page.ClientScript;
      csMngr.RegisterStartupScript(Page.GetType(), "Success", "alert('Record Added succesfully');", true);
}

ASPX Code for data grid

<asp:DataGrid ID="grdEmp" runat="server">
<HeaderStyle CssClass="Header" />
<AlternatingItemStyle CssClass="AlternateItemStyle" />
</asp:DataGrid>

Write below code to bind the data into DataGrid.

private void bindData()
{
SqlConnection con = null;
SqlDataAdapter adp = null;
try
{
con = new SqlConnection(conString);
con.Open();
adp = new SqlDataAdapter("Select * from Employee",con);
DataSet ds = new DataSet();
adp.Fill(ds);
grdEmp.DataSource = ds;
grdEmp.DataBind();
}
catch (CustomException ex)
{
ex.logException();
}finally{
con.Close();
}
}

Final output:

Download Code

ASP.NET DataGrid basic questions

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 2 Comments on ASP.NET DataGrid basic questions
  1. What is datagrid? The DataGrid Web server control is a powerful tool for displaying information from a data source. It is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. At the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data.
  2. What’s the difference between the System.Web.UI.WebControls.DataGrid and System.Windows.Forms.DataGrid? The Web UI control does not inherently support master-detail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one.
  3. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row.
  4. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grid’s AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the column’s DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting.
  5. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list “” for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
  6. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control’s TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.

You can find more questions on Datagrid at http://msdn.microsoft.com/en-us/library/Aa289519

Upload Files in ASP.NET at Production server

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , , , with Leave a comment on Upload Files in ASP.NET at Production server

In this article, i am going to demonstrate that how to upload the file in ASP.NET production server.

Most of the case, a developer created a code to upload the file and test it on his local machine. program runs smoothly, but as he forward the same code on production. He stuck in the file permission error as on the local he has the full permission whereas on development its not the case.

So i decided to write this tutorial for the beginners which will demonstrate lots of ASP.NET features.

First we need to create a folder in Server and share it with ASP.NET web server as described.

Right click on folder, select Web sharing tab and select the radio button “Share this folder”. One  window appear, give it alias name which will be used in coding.

After this, open Run box and type “inetmgr“. you will see that your web shared folder appears in the IIS.

Right click on folders property. one window will opened.

Select “Directory Security” tab then click on “Edit” button and then check “Anonymous access”. And because of this setting any body can access or download that file.

Now we are ready, to create a sample application which will demonstrate that how to upload the file and use it.

Create ASP.NET project in Visual Studio. Create a webpage with fileupload, hyperlink and button control.

<form id="form1" runat="server">
<asp:FileUpload ID="uploadFile" runat="server" /><br />
<asp:HyperLink ID="hypLink" runat="server" Visible="false" Target="_blank"></asp:HyperLink><br />
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" />
</form>

In web.config add two keys.  One for actual folder location in which we are going to upload the files and other its alias name. we can also hard code that, but its good practice to make it configurable at any time because in near future we may want to change the location.


<appSettings>

<add key="DemoAttachment" value="D:ShareDemoShare"></add>

<add key="DemoAttachmentVirtualPath" value="http://localhost/DemoShare/"></add>

</appSettings>

In DemoAttachmentVirtualPath key, value should like “http://machinename/” + Alias folder name.

On click event of button, write below code:

string strPath = ConfigurationManager.AppSettings["DemoAttachment"];
uploadFile.SaveAs(strPath + System.IO.Path.GetFileName(uploadFile.FileName));
hypLink.Visible = true;
string VirtualPath = ConfigurationManager.AppSettings["DemoAttachmentVirtualPath"];
hypLink.Text = System.IO.Path.GetFileName(uploadFile.FileName);
hypLink.NavigateUrl = VirtualPath + uploadFile.FileName;
string strPath = ConfigurationManager.AppSettings["DemoAttachment"];

uploadFile.SaveAs(strPath + System.IO.Path.GetFileName(uploadFile.FileName));
hypLink.Visible = true;
string VirtualPath = ConfigurationManager.AppSettings["DemoAttachmentVirtualPath"];

hypLink.Text = System.IO.Path.GetFileName(uploadFile.FileName);

hypLink.NavigateUrl = VirtualPath + uploadFile.FileName;

The output will look like:

Download Source code

For the file size limitation, please visit this article : https://jitendrazaa.com/blog/?p=125

cannot access a closed file – FileUpload in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with 15 Comments on cannot access a closed file – FileUpload in ASP.NET

This was very interesting error, i got during development of file upload control in ASP.NET.

On my local system, every thing was just fine. but when i deployed my application on development server, my control was able to upload only small size files.

whenever i tried to upload large size file i got error “cannot access a closed file”

After going through MSDN i found that there is one new element added in ASP.NET 2.0 known as httpRuntime.

So i just added this new Tag in my web.config and every thing was right.

<system.web>
<httpRuntime  maxRequestLength="15360" requestLengthDiskThreshold="15360"/>
</system.web>

Note :

requestLengthDiskThreshold should not exceed the maxRequestLengthattribute.

To read more about this, please visit http://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx

XML Parsing Error: no element found

Author posted by Jitendra on Posted on under category Categories ASP.NET, Tech Tips and tagged as Tags , with 3 Comments on XML Parsing Error: no element found

Few Days ago, i found strange error like “XML Parsing Error: no element found“.

I was unable to find the exact root cause. Most of the times it happens if you are missing any closing tag in your ASPZ application. I checked my complete page and reconfirmed but error still persist.

somehow i found that ASP.NET treat the response of page as XML document and that’s why we receive XML Parsing Error: no element found error.

so explicitly i set the response type of my page as text/HTML. Response.ContentType = “text/HTML”.

And this line tells the ASPX that page is HTML, not XML.

Style File upload control in ASP / HTML

Author posted by Jitendra on Posted on under category Categories HTML and tagged as Tags , , , with 2 Comments on Style File upload control in ASP / HTML

As most of us know that we cannot style the file upload control to much level, still we can give it a stunning effect with the help of CSS.

There is nothing in code to explain.

I took three upload control and one button to give effect.

Lets say upload control is in ASP.net or in HTML.

<asp:FileUpload ID="FileUpload1" CssClass="Cntrl1" runat="server" />
Or
html file upload
<input id="readFile" type="file" runat="server" class="Cntrl1" />

Then create a simple CSS class of name “Cntrl1”.

  <style id="cssStyle" type="text/css" media="all">
       .Cntrl1
      {
       background-color:#abcdef;
       color: Yellow;
       border: 1px solid #AB00CC;
       font: Verdana 10px;
       padding: 1px 4px;
       font-family: Palatino Linotype, Arial, Helvetica, sans-serif;
      }
</style>

Out put in different browsers will look like :

Output in Chrom
Output in Chrom
Output in Mozilla
Output in Mozilla
Output in Internet explorer
Output in Internet explorer

View Demo of FileUpload

ASP.Net Error: Response is not available in this context

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with 2 Comments on ASP.Net Error: Response is not available in this context

This error occurred when  i tried to call Response.Redirect method from a class file. Then i tried to find the solution and i got to know that when we use the response object from an aspx page either from aspx page or it’s codebehind page, the response object is directly available because all these derived from the page object.

When we use the response object in our own class, the object is not directly available, so we got this message.

But we can use it by the following method :

HttpContext.Current.Response.Redirect(http://google.com“);

Same problem happens when we tried to call a function from Response object.

Thank You.

App_Offline.htm in ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags with 1 Comment on App_Offline.htm in ASP.NET

If you place a file with the name App_Offline.htm in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the App_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

Once you remove the App_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and it will be back to normal.

If you place a file with the name App_Offline.htm in the root of a web application directory, ASP.NET 2.0 will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

ASP.NET will also then respond to all requests for dynamic pages in the application by sending back the content of the App_offline.htm file (for example: you might want to have a “site under construction” or “down for maintenance” message).

Once you remove the App_offline.htm file, the next request into the application will cause ASP.NET to load the application and app-domain again, and it will be back to normal.

Limitation:

Note that the file must be at least 512kb in size or it will not work. This a well known ‘limitation’.

Use FXcop with ASP.NET

Author posted by Jitendra on Posted on under category Categories ASP.NET and tagged as Tags , with Leave a comment on Use FXcop with ASP.NET

FxCop, an abbreviation “Framework Police,” is a rules-based engine that checks managed code assemblies for Microsoft’s .NET Framework design guidelines and custom guidelines. FxCop is a rule based engine which helps the development team to follow best practices of the .NET platform and development standards (based on every company standards).
You can apply to any assembly which been created using any language that target Microsoft.NET managed environment.

Advantages:

1.Make sure coding standards follow such as naming conventions, globalization etc. as per company standards.
2. Avoid bad coding. (No one write bad code however as the application grows development team size also grow usually so ever new team member must know how to design their classes, follow naming convention etc.).
3. Predefined set of rules.
4. Support for creating custom rules.
5. Generate formatted XML Analysis Report.

To use FxCop with ASP.NET, follow below steps:

Go to

C:WINDOWSMicrosoft.NETFrameworkv2.0.50727Temporary ASP.NET FilesMyTest

Where MyTest is your project folder

Select details view from Explorer so you can see which folder is the newer folder and open it up

Select details view again and hunt down the App_Web dll file that is the latest e.g.

App_Web_cxauo9ex.dll

You can then add this as a target in your FxCop project.