Search This Blog

Tuesday, July 22, 2014

Sorting in Gridview Control

Write the following code In .aspx page :


<asp:GridView ID="gvstudents" runat="server" AllowSorting="true" 

    OnSorting="gvstudents_sorting">

    </asp:GridView>

Code in .aspx.cs:


public partial class SortingEx : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            string strcon = "data source=name of sql server ;initial catalog=database name;integrated security=sspi or user id=sqlserver userid ; password=somepassword";
            string sConnection = strcon;
            DataSet ds = new DataSet();
            SqlConnection cn = new SqlConnection(sConnection);
            using (cn)
            {
                SqlCommand cmd = new SqlCommand("select * from employees", cn);
                using (cmd)
                {
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    da.Fill(ds);
                    gvstudents.DataSource = ds;
                    gvstudents.DataBind();
                    Session["ds"] = ds;
                    ViewState["sortcolumn"] = string.Empty;
                    ViewState["sortdirection"] = string.Empty;
                }
            }
        }
    }
    protected void gvstudents_sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["ds"] != null)
        {
           DataSet ds = (DataSet)Session["ds"];
           DataTable dt = ds.Tables[0];
           DataView dv = dt.DefaultView;//DataView ado.net view in t-sql 
            if (ViewState["sortcolumn"].ToString() == e.SortExpression.ToString())
            {
                if ("asc" == ViewState["sortdirection"].ToString())
                {
                    ViewState["sortdirection"] = "DESC";
                }
                else
                {
                    ViewState["sortdirection"] = "asc";
                }
            }
            else
            {
                ViewState["sortcolumn"] = e.SortExpression.ToString();
                ViewState["sortdirection"] = "asc";
            }
            if (dv != null)
            {
                dv.Sort = e.SortExpression + " " + ViewState["sortdirection"].ToString();
                //dv.Sort= "ename asc";
                gvstudents.DataSource = dv;
                gvstudents.DataBind();
            }
        }

    }
}

Table structure :

eidfnamelnameagesalarydeptdoj
1rajeevsukla2312000.net23-Oct-11 12:00:00 AM
2sowmyakumari2319000db13-Nov-10 12:00:00 AM
3kishorekumar2736000android16-Oct-11 12:00:00 AM
4abimanyubiswal22nullandroid20-Feb-10 12:00:00 AM
5sonikumar2421800.net21-Jun-09 12:00:00 AM
6anu_singh2212000db23-Oct-10 12:00:00 AM
7_dineshmoh%anty2315000.net26-Aug-09 12:00:00 AM
8nishala_kumari2218000db19-Jul-08 12:00:00 AM
1rajeevsukla2312000.net23-Oct-11 12:00:00 AM

Monday, July 21, 2014

Asp.net Gridview edit update and delete code

In GridViewEditUpdateDelete.aspx add the following code ( in the form tag )


<asp:GridView ID="gvPatients" AutoGenerateColumns="false" runat="server"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
    DataKeyNames="PatientID"
        onrowediting="gvPatients_RowEditing"
        OnRowCancelingEdit="gvPatients_RowCancel" OnRowUpdating="gvPatients_RowUpdating"
        OnRowDeleting="gvPatients_RowDeleting"
        onselectedindexchanged="gvPatients_SelectedIndexChanged">
    <HeaderStyle BackColor="AliceBlue" ForeColor="Red"/>
    <Columns>
    <asp:TemplateField HeaderText="PatientID">
    <ItemTemplate>
    <asp:Label ID="lblPatientID" runat="server" Text='<%#Eval("PatientID") %>'/>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="PatientName">
    <EditItemTemplate>
    <asp:TextBox ID="tbName" runat="server" Text='<%#Eval("PatientName")%>' />
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"PatientName")%>' />
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="AGE">
    <EditItemTemplate>
    <asp:TextBox ID="tbAge" runat="server" Text='<%#Eval("age")%>' />
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="lblAge" runat="server" Text='<%#Eval("age")%>' />
    </ItemTemplate>
    </asp:TemplateField>  
    </Columns>
    </asp:GridView>


In .aspx.cs page add the following code:


public partial class DataGridColumns : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillPatientInfo();
        }
    }
    private void FillPatientInfo()
    {
        //bad approach for getting connection string.
        string strcon = "data source=your sql server name ;initial catalog=your database name ;integrated security=sspi";
        SqlConnection cn = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("select * from patient", cn);
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        da.Fill(ds);
        gvPatients.DataSource = ds;
        gvPatients.DataBind();
        Session["dsPatients"] = ds;
        //GridView1.DataSource = ds;
        //GridView1.DataBind();
    }
    protected void gvPatients_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvPatients.EditIndex = e.NewEditIndex;
        gvPatients.DataSource = (DataSet)Session["dsPatients"];
        gvPatients.DataBind();
    }
    protected void gvPatients_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblPatientID = (Label)gvPatients.Rows[e.RowIndex].FindControl("lblPatientID");
        SqlConnection cn = new SqlConnection("data source=ADMIN-PC\\SQLEXPRESS;initial catalog=palletechnologies;integrated security=sspi");
        SqlCommand cmd = new SqlCommand();
        StringBuilder sb = new StringBuilder();
        sb.Append("delete patient where patientid='" + lblPatientID.Text + "'");
        cmd.CommandText = sb.ToString();
        cmd.Connection = cn;
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        FillPatientInfo();
    }
    protected void gvPatients_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label lblPatientID = (Label)gvPatients.Rows[e.RowIndex].FindControl("lblPatientID");
        TextBox tbAge = (TextBox)gvPatients.Rows[e.RowIndex].FindControl("tbAge");
        TextBox tbName = (TextBox)gvPatients.Rows[e.RowIndex].FindControl("tbName");
        SqlConnection cn = new SqlConnection("data source=ADMIN-PC\\SQLEXPRESS;initial catalog=palletechnologies;integrated security=sspi");
        SqlCommand cmd = new SqlCommand();
        StringBuilder sb = new StringBuilder();
        sb.Append("update patient set patientname='" + tbName .Text+ "',");
        sb.Append("age='"+tbAge.Text+"' where patientid='"+lblPatientID.Text+"'");
        cmd.CommandText = sb.ToString();
        cmd.Connection = cn;
        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        gvPatients.EditIndex = -1;
        FillPatientInfo();
    }
    protected void gvPatients_SelectedIndexChanged(object sender, EventArgs e)
    {
        
    }
    protected void gvPatients_RowCancel(object sender, GridViewCancelEditEventArgs e)
    {
        gvPatients.EditIndex = -1;
        e.Cancel = true;
        gvPatients.DataSource = (DataSet)Session["dsPatients"];
        gvPatients.DataBind();
    }
}

Patient table structure: 

Create a patient table with PatientID,PatientName and Age columns.

Thursday, April 10, 2014

How to set startup url in asp.net mvc

1.Go to MVC web application property page and set Start Action Specific Page value equal to ControllerName/ActionMethodName ( refer below given screen shot )

Friday, December 20, 2013

What is an action method in MVC

An action method in mvc is a method which can able to redirect user to a view ( an action method can optionally pass model data to a view for rendering views ui filled with model data ).
OR
An action method is a method which is returning ActionResult .

Note: I For testing your knowledge in .net , c , cpp , aptitude , java and arithmetic you can visit the links present http://www.skillgun.com

Important links in skillgun .

arithmetic questions and answers
android interview questions and answers
c interview questions and answers
c++ interview questions and answers
java interview questions and answers
c# interview questions and answers

Tuesday, November 8, 2011

About Global.asax in ASP.NET


  • Global.asax is a file in asp.net
  • Global.asax file contains all the application level methods.like
  •       1.Application_Start 2.Application_End 3.Session_Start 4.Session_End etc..
  • Note: When you compile your code for the first time your ASP.NET runtime creates a class corresponding to Global.asax file with the Class name global_asax. This class inherits from HTTP Application class.
  • You can see the automatically created class in the C:\Documents and Settings\User\My Documents\Visual Studio 2008\WebSites\ApplicationName\global.asax file.

Friday, October 28, 2011

Adding new Nodes to XML File in C#

1.Create a Dummy xml file with the name Patients.xml in your solution explorer.
    Ex:
 <Patients>
  <Patient type="IP">
    <VistorNum>134</VistorNum>
    <FName>Maha</FName>
    <LName>Veer</LName>
    <Age>89</Age>
    <Sex>Male</Sex>
  </Patient>
</Patients>
 
2.Create the UI to accept data from users.(Write the below code in .aspx page)
   VisitorNum:<asp:TextBox ID="tbVstrNum" runat="server" ></asp:TextBox><br />
    FName:<asp:TextBox ID="tbFName" runat="server" ></asp:TextBox><br />
    LName:<asp:TextBox ID="tbLName" runat="server" ></asp:TextBox><br />
    Age:<asp:TextBox ID="tbAge" runat="server" ></asp:TextBox><br />
    Sex:<asp:TextBox ID="tbSex" runat="server" ></asp:TextBox><br />
    <asp:Button ID="btnInsertPat" Text="AddPatient" runat="server" 
            onclick="btnInsertPat_Click" />
3.Write the below code in code behind's button click method.
    protected void btnInsertPat_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("Patients.xml"));
        //Create a New patient node.
        XmlNode nPatient=doc.CreateNode(XmlNodeType.Element,"Patient",null);
        //Create visitornUm,FName,LName,Age,Sex nodes and add 
        //it to Patient Node
        XmlElement eVistNum= doc.CreateElement("VistorNum");
        eVistNum.InnerText = tbVstrNum.Text;
        XmlElement eFName = doc.CreateElement("FName");
        eFName.InnerText = tbFName.Text;
        XmlElement eLName = doc.CreateElement("LName");
        eLName.InnerText = tbLName.Text;
        XmlElement eAge = doc.CreateElement("Age");
        eAge.InnerText = tbAge.Text;
        XmlElement eSex = doc.CreateElement("Sex");
        eSex.InnerText = tbSex.Text;
        nPatient.AppendChild(eVistNum);
        nPatient.AppendChild(eFName);
        nPatient.AppendChild(eLName);
        nPatient.AppendChild(eAge);
        nPatient.AppendChild(eSex);
        //Get the Root Patients Node ref.
        XmlNode root=doc.SelectSingleNode("Patients");
        //Add New patient node to root patient node.
        root.AppendChild(nPatient);
        string sPath = Server.MapPath("Patients.xml");
        doc.Save(sPath);
        //elem.AppendChild(
    }
Sign Up for dot net training course 

Friday, September 9, 2011

Opening My Computer Using ASP.NET

Please use the HTML Input File Control for opening all the available Drives. Just Drag and drop the control
on to the .aspx page and check the result by clicking on the Browse Button.

India's #1 .NET Training