-->

Friday, May 29, 2015

How to bind html table in asp.net c#

In previous article we have already learn about binding but all they have a data bound control like Gridview, FormView etc. Today i am talking about html table. In my previous article , i was already write something about html tag and their uses also write that how to use html tag in code behind file of webform. In this article we have new concept that is StringBuilder class. By the help of this class we can do any changes in single object. I mean to say that a single object hold large string. Now see a simple example of html table binding:


Source Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>

Here,

  1. Add a new webform in the website.
  2. Add a placeHolder control in the page. Put some control in code behind file.


Code behind code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    StringBuilder table = new StringBuilder();

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select * from [country]";
            cmd.Connection = con;
            SqlDataReader rd = cmd.ExecuteReader();
            table.Append("<table border='1'>");
            table.Append("<tr><th>Country Id</th><th>Country Name</th>");
            table.Append("</tr>");

            if(rd.HasRows)
            {
                while(rd.Read())
                {
                    table.Append("<tr>");
                    table.Append("<td>" + rd[0] + "</td>");
                    table.Append("<td>" + rd[1] + "</td>");
                    table.Append("</tr>");
                }
            }
            table.Append("</table");
            PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
            rd.Close();
        }
    }
}
Code Generate the following output
How to bind html table in asp.net c#

According to the mentioned code we have a object of StringBuilder class, through this we have to create a html table with the help of Append( ) method. By the SqlDataReader class read data one by one also insert into html table. Now, add a Literal control in the placehoder along with StringBuilder class object.

Thursday, May 28, 2015

How to delete row of Gridview using Link button in ASP.NET C#

Good morning friends, I have covered many article on Gridview binding. Today i am talking about Gridview with link button.In this article we will do something different like delete row when we press the delete link button. To do this task, first to design the Gridview with link button after that perform some operation on link button.


Source Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<script>
function ConfirmationBox(countryname) {

var finalresult = confirm('Are you sure you want to delete' + countryname + 'details');
if (finalresult) {
return true;

}
else {
return false;
}
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="CountryId" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CountryId" HeaderText="Country Id" />
<asp:BoundField DataField="CountryName" HeaderText="Country Name" />
<asp:TemplateField HeaderText="delete">
<ItemTemplate>

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Delete Country</asp:LinkButton>

</ItemTemplate>

</asp:TemplateField>
</Columns>
</asp:GridView>
    </div>
    </form>
<p>
&nbsp;</p>
</body>
</html>

In the above mentioned code we have a script block which is used for giving confirmation message  when we click on link button. Also we have a Gridview with three column , first two starting columns bind with the country table, in the  third column we have a delete link button.


CodeBehind Code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    DataSet ds;

    public Default3()
    {
        con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        cmd = new SqlCommand();
        ds = new DataSet();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            bindgridview();
        }
    }

    private void bindgridview()
    {
        con.Open();
        cmd.CommandText = "select * from [country]";
        cmd.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        con.Close();
        GridView1.DataSource = ds;
        GridView1.DataBind(); 
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType==DataControlRowType.DataRow)
        {
            string countryname = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CountryName"));
            LinkButton lnkbutton = (LinkButton)e.Row.FindControl("LinkButton1");
            lnkbutton.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + countryname + "')");
        }

    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        LinkButton lnk = sender as LinkButton;
        GridViewRow gridrow = lnk.NamingContainer as GridViewRow;
        int countryid = Convert.ToInt32(GridView1.DataKeys[gridrow.RowIndex].Value.ToString());
        con.Open();
        cmd.CommandText = "delete from [country] where CountryId=" + countryid;
        cmd.Connection = con;
        int a = cmd.ExecuteNonQuery();
        con.Close();
        if(a>0)
        {
            bindgridview();
        }
    }
}
Output of the following mentioned code


How to delete row of Gridview using Link button in ASP.NET C#


 In the above mentioned code, first to bind the gridview with the DataSet. By the RowDataBound event we have to generate confirmation message using java script. So first of all get the country name by the eval method. Also get the link button from Gridview using findControl( ) method. Now you can call javaScript method on LinkButton

By the help of link button event handler we are deleting the row from the Gridview which is mentioned in the code. So first of all get the countryid from the binded gridview then execute delete statement.

How to design online examination project in asp.net c#

Before design the system, must to prepare the database. If you want to design the database then must to know about the system requirements so I have a system requirements:
Hardware System: Core i3 processor for better performance.
Software System:  Visual studio 2013 or higher like visual studio 2015 CTP.
Application Requirements: Design a software application through which we can conduct exam online, in which we have two module, one for students and one for administrator. In the student module, first to authorized student login in the system after that choose subject by the pop up menu. After some time exam panel will appear on the screen, students can select one option at a time. After complete the exam student can see the own result. Also provide the help system to the student, in which an authorized person can put the query to the administrator. An administrator module provide some following function:
  • 1.       Add new student
  • 2.       Change password module
  • 3.       Add new Subject
  • 4.       Update question size
  • 5.       Respond to the user query
  • 6.       See the result of the students

So, after finishing the requirements should go for database design part. First of all I would like to discussed about register and login table and many more tables , to design the table in visual studio please follow the following path
Right click on your table nameà Add new table à After add column in the table please click “update” button.
 Register table:
 In the register table , according to visual studio snap which is mentioned below. We have six columns. Which name are , mid, lname, pwd, full name, email, and dlv. Mid means member id , which is unique and primary key of the table. Through this table we will perform registration in the system. Mid column contain only integer type value and all remaining columns contain variable types characters with their character range.
Login table:

Register table is used for member login, so it’s not a separate table in the server explorer.

Register table:


Questions table:
Through this table we will put questions in the examination panel. This table also contain answer and subject id column. Through this we can access the specific subject in the panel.  In this table we have 8 columns which is given below in the snap. qid column Is the primary key column of the table, so we can easily identify the uniqueness of the record. In the Question column we will put some question along with their answers in the answers column. “cans” means correct answers, I mean to say put the correct answer number in the column, such as if your first answer is correct then put 1 in the column. “sid” means subject id. The next table define the subject which is mentioned in the project.

Questions table:


  Subject Table :
In this table we have only two columns, these are “sid” and “sname”. Sid means subject id and sname means subject name.  Please carefully insert the data in this table because all other remaining table are related to this table via foreign key.  Question table is also mapped with this table
  Subject Table :

Exam table:
In this table we will store the result of the examination. A student who give the exam by the exam panel.
In it we will store the examid, member_id, sid, no of question, no of correct answer and date.
Now , finish the database design and come to the design part of the project. First to design the master page in the project. Now, learn how to add a master page in the project. Please follow the following path:
Right click on your project nameà Select add new itemà select masterpage , which extension is .master.  A small description of master page.
Master page
One of the cool new things introduced in ASP.NET 2.0 is Master Pages. Master Pages give you the ability to define a master page layout and look that is used throughout a site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page.

A master page is similar to an ordinary ASP.NET page except for the top @Master directive and the presence of one or more ContentPlaceHolder server controls. A ContentPlaceHolder

control defines a region in the master page that can be customized in a derived page. ContentPlaceHolder acts as container which holds controls/items defined in the derived pages. <asp:contentplaceholder runat="server" ID="PageBody" />

In the derived pages, server control <asp:Content> is used to provide actual content to ContentPlaceHolders of Master Page. The link between placeholders and content is established through the Content place holder ID.

<asp:Content runat="server" contentplaceholderID="PageBody">
...
</asp:Content>
In the master page we have a style sheet , through it we can change the graphics of the web project or you can say layout or design of the project.In this project style is exist in the style folder. Now take a look of the style sheet , which extension is .css.
.page{
    width:900px;
    margin: 0px auto 0px auto;


}
In this we have we have a class which is start from dot. In the class we have some property , through this we can set the layout of the project. In the above mentioned snap , I set the width of the project is 900px and margin of the project.
Now come to the next part that is navigation part, through this we can move the next page of the project like
Home-à aboutàContactàuseràadminàUser help
Learn, how to design navigation bar in the project. Add a menu control from the toolbox , add some items like home, about, contact etc in the menu by the help of collection property. Also set the oriention property of the menu is horizontal. Lets take a look of menu bar.

Now come to the next phase is user login module , but user is logged in when he/she is authorized.
So first to discussed about admin panel. Now, create a new folder name admin. In it add new master page for administrator interface.

In the above mentioned snap we have a master page whose name is mianadmin.aspx. This master page is also inherit from previous master page which is exist in the root folder. Add a html table from the tool box and also add new content place holder from the toolbox. In the left panel, add a menu control for navigation purpose. Add some items in the menu control like

BY the Add User hyperlink we can navigate to the register page , where admin add new students in the database. So lets to talk about how to register a new student in the database. Create a student register form with the help of tool box in the .ascx file. In this project we add a new .ascx file in the web user control folder.  Lets to learn how to perform registration in the asp.net.
Registration:
  • 1.       First to create a object of SqlConnection class, that object invoke the method and property of the SqlConnection class.
  • 2.       By the help of coneection string property we have to create the connection between the front to back end.
  • 3.       Create a sqlCommand class , through which we can communicate with the database table.
  • 4.       By the help of ExecuteNonQuery ( ) method , we will insert the item in the databse.

If user is successfully registered by the admin then user logged in the  examination panel with the help of login page.
Login page:
1.       First to create a object of SqlConnection class, that object invoke the method and property of the SqlConnection class.
2.       By the help of coneection string property we have to create the connection between the front to back end.
3.       Create a sqlCommand class , through which we can communicate with the database table.
4.       By the help of executeReader() method , we can read rows one by one. So we can easily find the data in the table.
After successfully login , student move the exam panel where who give the answers of the question , So lets to talk about design of the examination page.
  • 1.       Add some label control for student name, date , question name etc.
  • 2.       Add four radio button for answers option.
  • 3.       Add a sql DataSource control to connect the Question table.

When student give the answer by the radio button then he/she store the result in the tempary variable, I mean to say in this project we have two temporary variable first is used for wrong answer and second one is used for correct answer.
Now calculate the correct answer and wrong answer , after that it will store in the exam table. This table see by the student immediately after the end of examination. Also this table see by the administrator.
User Help:
By the user help form, user request put some request to the admin. So for this type of query we will add a form view control in the page from the tool box control. Bind this form view with the sql data source control. 


Monday, May 25, 2015

College website project in asp.net c#

College website project provide the right information to the existing student and new comers. The main aim of this project is to provide such types of information which is mentioned below:

  1. Current news
  2. Home slide section
  3. About panel 
  4. Contact us panel
In this project i have two module, first is student module and last one is administrator module. Student can see all the details which is mentioned on the website. Through admin module we can update the website time to time , when we need.
Home page of the website :

Home page contains all such information which is important to the student and their parents. In this project we have two panel (left panel and right panel). In the right side bar we have news section , through which we give the right and updated information to the students also contain administrator login panel

How to run the project under visual studio 2013 or higher

.


Hardware and software requirements

  1. Hardware : Core i3 pc
  2. Software  : Visual studio 2013 with sql server 2008
Download :  Purchase it in 500 RS or 15$ 
Mail me : narenkumar851@gmail.com

Friday, May 15, 2015

How to create cookies in asp.net c#

If you want to create individual item cookie then use HttpCookie class , which is available in System.Web namespace. There are two object to use get and set cookie in the computer that are Request and Response. By using Request object  we can get the cookie from the computer and By using Response object we can create new cookie in the computer.

Create cookie for individual item:

HttpCookie cookie = new HttpCookie("mycookie");
        cookie.Value = "Hello World";
        cookie.Expires = DateTime.Now.AddMinutes(10d);
        Response.Cookies.Add(cookie);

Here,

  • cookie is the instance of HttpCookie class, By using this we can invoke properties of this class.
  • mycookie is a name of  the cookie.
  • This cookie will expired just after 10 minute.
  • Add new cookie by the Response object. 
Retrieve cookie which is stored in computer

     HttpCookie cookie =Request.Cookies.Get("mycookie");
        Response.Write(cookie.Value.ToString());

Create cookie for multiple item :

 Response.Cookies["username"].Value = "Jacob";
        Response.Cookies["username"].Expires = DateTime.Now.AddMinutes(10d);
        Response.Cookies["password"].Value = "Lefore";
        Response.Cookies["password"].Expires = DateTime.Now.AddMinutes(10d); 

Retrieve multiple cookie item:

  HttpCookieCollection cookies = Request.Cookies;
        for (int i = 0; i < cookies.Count; i++)
        {
            Response.Write(cookies[i].Name.ToString() + "<br/>");
            Response.Write(cookies[i].Value.ToString() + "<br/>");
        }

Code generate the following output

How to create cookies in asp.net c#

How to load multiple data table in DataSet

ASP.NET C# : Load multiple data table in DataSet. If you want to add multiple table in DataSet then need two SqlDataAdapter for DataSet.
Source code :

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    </div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add multiple table in dataSet" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
        <asp:GridView ID="GridView2" runat="server"></asp:GridView>
    </form>
</body>
</html>

Code Behind Code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        con.Open();

        SqlDataAdapter productadapter = new SqlDataAdapter();
        productadapter.TableMappings.Add("Table", "Suppliers");
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select * from [Suppliers]";
        cmd.Connection = con;
        productadapter.SelectCommand = cmd;
        DataSet ds = new DataSet();
        productadapter.Fill(ds);

        SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.TableMappings.Add("Table", "Products");
        SqlCommand cmd1 = new SqlCommand();
        cmd1.CommandText = "Select * from [Products]";
        cmd1.Connection = con;
        adapter.SelectCommand = cmd1;
     
        adapter.Fill(ds);

        con.Close();

        GridView1.DataSource = ds.Tables["Products"];
        GridView1.DataBind();

        GridView2.DataSource = ds.Tables["Suppliers"];
        GridView2.DataBind();




    }
}
Code Generate the following output


How to load multiple data table in DataSet

Thursday, May 14, 2015

Hyperlink field Example of ASP.NET Grid View

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="JobId" DataSourceID="SqlDataSource1">
            <Columns>
                <asp:BoundField DataField="JobId" HeaderText="JobId" InsertVisible="False" ReadOnly="True" SortExpression="JobId" />
                <asp:BoundField DataField="JobName" HeaderText="JobName" SortExpression="JobName" />
                <asp:BoundField DataField="AboutJob" HeaderText="AboutJob" SortExpression="AboutJob" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" SortExpression="Salary" />
                <asp:HyperLinkField DataNavigateUrlFields="JobId" DataNavigateUrlFormatString="Default2.aspx?JobId={0}" HeaderText="Click to view " Text="details" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [JobId], [JobName], [AboutJob], [Salary] FROM [AddJob]"></asp:SqlDataSource>
   
    </div>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="JobId" DataSourceID="SqlDataSource2">
            <Columns>
                <asp:BoundField DataField="JobId" HeaderText="JobId" InsertVisible="False" ReadOnly="True" SortExpression="JobId" />
                <asp:BoundField DataField="JobName" HeaderText="JobName" SortExpression="JobName" />
                <asp:BoundField DataField="AboutJob" HeaderText="AboutJob" SortExpression="AboutJob" />
                <asp:BoundField DataField="Experience" HeaderText="Experience" SortExpression="Experience" />
                <asp:BoundField DataField="Qualification" HeaderText="Qualification" SortExpression="Qualification" />
                <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
                <asp:BoundField DataField="FunctionalArea" HeaderText="FunctionalArea" SortExpression="FunctionalArea" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" SortExpression="Salary" />
                <asp:BoundField DataField="Contact_person" HeaderText="Contact_person" SortExpression="Contact_person" />
                <asp:BoundField DataField="Contact_Person_Numer" HeaderText="Contact_Person_Numer" SortExpression="Contact_Person_Numer">
                <ControlStyle Width="10px" />
                <ItemStyle Width="50px" />
                </asp:BoundField>
                <asp:BoundField DataField="Email_id" HeaderText="Email_id" SortExpression="Email_id" />
                <asp:BoundField DataField="Work" HeaderText="Work" SortExpression="Work" />
                <asp:BoundField DataField="company_name" HeaderText="company_name" SortExpression="company_name" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [AddJob] WHERE ([JobId] = @JobId)">
            <SelectParameters>
                <asp:QueryStringParameter Name="JobId" QueryStringField="JobId" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
    </form>
</body>
</html>

Code generate the following output

Hyperlink field  Example of ASP.NET Grid View


© Copyright 2013 Computer Programming | All Right Reserved