0

Print Printing DataGridView In WinForms C# VB.NET Windows Application

Print Datagridview in winforms windows application using C# and vb.net
Printing DataGridView With C# VB.NET In Winforms Windows Froms Application.

In this post i'm explaining how to print datagridview in winforms windows application using C# and VB.NET with PrintDocument class.

Drag and place one DataGridView on the form and populate datagridview from database or dataset. I have used northwind database to populate datagridview.

Place one button on the form and name it btnPrint, we will print datagridview in Click event of this button so generate button's click event by double clicking on it.

Drag and place one PrintDocument control on the form from toolbox under printing tab, Double click on it to generate it's PrintPage event.


Printing Datagridview in C# vb.NET

Write below mentioned code in Click event of print button and PrintPage event of PrintDocument respectively.

c# CODE
private void btnPrint_Click(object sender, EventArgs e)
        {
            printDocument1.Print();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            PaintEventArgs gridSize = new PaintEventArgs(e.Graphics, new Rectangle(new Point(0, 0), this.Size));
            this.InvokePaint(dataGridView1, gridSize);
        }

VB.NET CODE
Private Sub btnPrint_Click(sender As Object, e As EventArgs)
 printDocument1.Print()
End Sub

Private Sub printDocument1_PrintPage(sender As Object, e As System.Drawing.Printing.PrintPageEventArgs)
 Dim gridSize As New PaintEventArgs(e.Graphics, New Rectangle(New Point(0, 0), Me.Size))
 Me.InvokePaint(dataGridView1, gridSize)
End Sub

Build and run the code.

0

Hide Disable Commandfield Or ButtonField In GridView Asp.Net

Conditionally Hide or disable Gridview commandfield buttonfield in asp.net
Conditionally Hide Or Disable GridView CommandField Or ButtonField Programmatically In Asp.Net Using C# And VB.NET

In this post i'm going to explain how to hide or disable commandfield or Buttonfirld such as Select button or ShowEditButton conditionally or programmatically in Gridview.

I'll also show how to hide or disable controls in TemplateField.

For this example i have used Northwind Databse to populate GridView.


I have enable selection from smart tag in design mode to show SelectButton Hyperlink in Gridview.

I will hide this select button where country name is equal to Mexico and disable it where country name is equal to Germany in any row of gridview as shown above in image.

I will also hide and disable checkbox placed in ItemTemplate.


HTML SOURCE OF GRIDVIEW
   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                DataSourceID="sqlDataSourceGridView" 
   3:                onrowdatabound="GridView1_RowDataBound" 
   4:                AutoGenerateColumns="false">
   5:  <Columns>
   6:  <asp:CommandField ShowSelectButton="True"/>
   7:              
   8:  <asp:TemplateField>
   9:  <ItemTemplate>
  10:  <asp:CheckBox ID="chkSelect" runat="server" 
  11:             Visible='<%# ShowHide(Eval("Country"))%>'/>
  12:  </ItemTemplate>
  13:  </asp:TemplateField>
  14:  <asp:BoundField DataField="CustomerID" 
  15:                  HeaderText="Customer ID"/>
  16:  <asp:BoundField DataField="City" HeaderText="city"/>
  17:  <asp:BoundField DataField="Country" 
  18:                  HeaderText="Country"/>
  19:  </Columns>
  20:  </asp:GridView>
  21:                 
  22:  <asp:SqlDataSource ID="sqlDataSourceGridView" 
  23:                     runat="server" 
  24:                     ConnectionString=
  25:  "<%$ ConnectionStrings:northWindConnectionString %>" 
  26:  SelectCommand="SELECT [CustomerID], [City], [Country] 
  27:                 FROM [Customers]">
  28:  </asp:SqlDataSource>

C# CODE
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string country = DataBinder.Eval(e.Row.DataItem, "Country").ToString();
            if (country == "Mexico")
            {
               
                LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
                lb.Visible = false;
            }
            else if (country == "Germany")
            {
                e.Row.Cells[0].Enabled = false;
            }

        }
    }

    protected bool ShowHide(object country)
    {
        if (country.ToString() == "France")
            return false;
        else
            return true;
    }


VB.NET CODE
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.DataRow Then
  Dim country As String = DataBinder.Eval(e.Row.DataItem, "Country").ToString()
  If country = "Mexico" Then

   Dim lb As LinkButton = DirectCast(e.Row.Cells(0).Controls(0), LinkButton)
   lb.Visible = False
  ElseIf country = "Germany" Then
   e.Row.Cells(0).Enabled = False

  End If
 End If
End Sub

Protected Function ShowHide(country As Object) As Boolean
 If country.ToString() = "France" Then
  Return False
 Else
  Return True
 End If
End Function

0

ExecuteNonQuery ExecuteScalar ExecuteReader Example

SqlCommand ExecuteNonQuery, ExecuteScalar, ExecuteReader and ExecuteXmlReader Method Examples in Asp.Net C# VB.Net.

1. SqlCommand ExecuteNonQuery Example
SqlCommand ExecuteNonQuery Method Example in Asp.Net.

In this post i'm explaining how and when to use ExecuteNonQuery method of SqlCommand in asp.net using C# and VB.NET.

2. SqlCommand ExecuteScalar Example
SqlCommand ExecuteScalar Method Example in Asp.Net Using C# and VB.Net

In this example i'mexplaining when and how to use SqlCommand ExecuteScalar method in asp.net.

3. ExecuteReader Example
SqlCommand ExecuteReader Method Example in Asp.Net Using C# And Vb.Net

In this example i'm explaining where and how to use ExecuteReader Method of SqlCommand in asp.net using C# and VB.NET.

4. SqlCommand ExecuteXmlReader Example
In this post i'm explaining how to use ExecuteXmlReader method of SqlCommand in asp.net.


0

Read Write XML File Using C# VB.NET In Asp.Net

Read write xml file in asp.net using c# vb.Net
Read And Write XML File Using C# VB.NET In Asp.Net

In this post i'm explaining how to read and write XML data from XML file in asp.net using C# and VB.Net.

For this example i have created a aspx page with three textbox to enter Details

Two buttons to read and write data xml file in click event of buttons.

I'm using Label control to display XML file data after reading it.


HTML SOURCE OF PAGE
   1:  <div>
   2:  Employee Details:
   3:   
   4:  Name:
   5:  <asp:Textbox id="txtName" runat="server"/>
   6:   
   7:  Department:  
   8:  <asp:Textbox id="txtDept" runat="server"/>
   9:   
  10:  Location:  
  11:  <asp:Textbox id="txtLocation" runat="server"/>
  12:   
  13:  <asp:Button ID="btnWriteXml" runat="server" 
  14:              Text="Write XML File" 
  15:              onclick="btnWriteXml_Click"/>
  16:   
  17:  Read XML File :
  18:  <asp:Button id="btnReadXml" text="Read XML File" 
  19:              runat="server" 
  20:              onclick="btnReadXml_Click"/>
  21:   
  22:  <asp:label id="lblXml" runat="server"/>
  23:   
  24:  </div>

Write below mentioned code in click event of read and write buttons respectively.

C# CODE

using System;
using System.Xml;
using System.Text;

protected void btnReadXml_Click(object sender, EventArgs e)
    {
        ReadXmlFile(Server.MapPath("EmployeeDetails.xml"));
    }
    protected void btnWriteXml_Click(object sender, EventArgs e)
    {
        XmlTextWriter xmlWriter = new XmlTextWriter(Server.MapPath("EmployeeDetails.xml"), Encoding.UTF8);
        xmlWriter.WriteStartDocument();
        //Create Parent element
        xmlWriter.WriteStartElement("EmployeeDetails");
        //Create Child elements
        xmlWriter.WriteStartElement("Details");
        xmlWriter.WriteElementString("Name", txtName.Text);
        xmlWriter.WriteElementString("Department", txtDept.Text);
        xmlWriter.WriteElementString("Location", txtLocation.Text);
        xmlWriter.WriteEndElement();

        //End writing top element and XML document
        xmlWriter.WriteEndElement();
        xmlWriter.WriteEndDocument();
        xmlWriter.Close();
    }

    protected void ReadXmlFile(string xmlFile)
    {
        string parentElementName = "";
        string childElementName = "";
        string childElementValue = "";
        bool element = false;
        lblXml.Text = "";
        
        XmlTextReader xmlReader = new XmlTextReader(xmlFile);
        while (xmlReader.Read())
        {
            if (xmlReader.NodeType == XmlNodeType.Element)
            {
                if (element)
                {
                   parentElementName = parentElementName + childElementName + "
";
                }
                element = true;
                childElementName = xmlReader.Name;
            }
            else if (xmlReader.NodeType == XmlNodeType.Text | xmlReader.NodeType == XmlNodeType.CDATA)
            {
                element = false;
                childElementValue = xmlReader.Value;
                lblXml.Text = lblXml.Text + "" + parentElementName + "
" + childElementName + "
" + childElementValue;
                parentElementName = "";
                childElementName = "";
            }
        }
        xmlReader.Close();
    }

VB.NET CODE

Protected Sub btnReadXml_Click(sender As Object, e As EventArgs)
 ReadXmlFile(Server.MapPath("EmployeeDetails.xml"))
End Sub
Protected Sub btnWriteXml_Click(sender As Object, e As EventArgs)
 Dim xmlWriter As New XmlTextWriter(Server.MapPath("EmployeeDetails.xml"), Encoding.UTF8)
 xmlWriter.WriteStartDocument()
 'Create Parent element
 xmlWriter.WriteStartElement("EmployeeDetails")
 'Create Child elements
 xmlWriter.WriteStartElement("Details")
 xmlWriter.WriteElementString("Name", txtName.Text)
 xmlWriter.WriteElementString("Department", txtDept.Text)
 xmlWriter.WriteElementString("Location", txtLocation.Text)
 xmlWriter.WriteEndElement()

 'End writing top element and XML document
 xmlWriter.WriteEndElement()
 xmlWriter.WriteEndDocument()
 xmlWriter.Close()
End Sub

Protected Sub ReadXmlFile(xmlFile As String)
 Dim parentElementName As String = ""
 Dim childElementName As String = ""
 Dim childElementValue As String = ""
 Dim element As Boolean = False
 lblXml.Text = ""

 Dim xmlReader As New XmlTextReader(xmlFile)
 While xmlReader.Read()
  If xmlReader.NodeType = XmlNodeType.Element Then
   If element Then
    parentElementName = parentElementName & childElementName & "
"
   End If
   element = True
   childElementName = xmlReader.Name
  ElseIf xmlReader.NodeType = XmlNodeType.Text Or xmlReader.NodeType = XmlNodeType.CDATA Then
   element = False
   childElementValue = xmlReader.Value
   lblXml.Text = lblXml.Text + "" & parentElementName & "
" & childElementName & "
" & childElementValue
   parentElementName = ""
   childElementName = ""
  End If
 End While
 xmlReader.Close()
End Sub


Download Sample Code



1

Check UserName Email Availability In Asp.Net Using Ajax

check username email availability using ajax in asp.net
Check Username or Email availability in asp.net using Ajax C# and VB.Net


In this post i'm explaining how to check username or email availability using ajax in asp.net user registration page.

You may also like to read one of my previous posts where i described how to Create User Registration Form In AspNet.

For this example create a table Users in sql server database with ID,Username and Email columns and add some records in it.

Drag and Place ScriptManager and Ajax UpdatePanel on the page, and inside ContentTemplate of update panel place two textbox for username and email, two image control to display images and two label control to display related messages.


Set AutoPostBack property of textbox to true.

HTML SOURCE OF PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   4:  </div>
   5:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
   6:  <ContentTemplate>
   7:  <table><tr><td>UserName: </td>
   8:  <td>
   9:  <asp:TextBox ID="txtUserName" runat="server" 
  10:               ontextchanged="txtUserName_TextChanged" 
  11:               AutoPostBack="True">
  12:  </asp:TextBox></td>
  13:  <td>
  14:  <asp:Image ID="imgUser" runat="server" Visible="false"/>
  15:  </td>
  16:  <td><asp:Label ID="lblUser" runat="server"/></td></tr>
  17:   
  18:  <tr><td>Email ID: </td>
  19:  <td>
  20:  <asp:TextBox ID="txtEmail" runat="server" 
  21:               AutoPostBack="True" 
  22:               ontextchanged="txtEmail_TextChanged">
  23:  </asp:TextBox></td>
  24:  <td>
  25:  <asp:Image ID="imgEmail" runat="server" Visible="false"/>
  26:  </td>
  27:  <td><asp:Label ID="lblEmail" runat="server"/></td></tr>
  28:  </table>
  29:  </ContentTemplate>
  30:  </asp:UpdatePanel>
  31:  </form>

Write below mentioned code in TextChanged Event of Username textbox

C# CODE
protected void txtUserName_TextChanged(object sender, EventArgs e)
    {
        if (txtUserName.Text != string.Empty)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string strSelect = "SELECT COUNT(*) FROM Users WHERE Username = @Username";
            SqlConnection con = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(strSelect,con);

            SqlParameter username = new SqlParameter("@Username", SqlDbType.VarChar);
            username.Value = txtUserName.Text.Trim().ToString();
            cmd.Parameters.Add(username);
            con.Open();
            int result = (Int32)cmd.ExecuteScalar();
            con.Close();

            if (result >= 1)
            {
                imgUser.ImageUrl = "unavailable.png";
                imgUser.Visible = true;
                lblUser.Text = "Username not available";
                lblUser.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                imgUser.ImageUrl = "tick.png";
                imgUser.Visible = true;
                lblUser.Text = "Available";
                lblUser.ForeColor = System.Drawing.Color.Green;
            }
        }
    }

VB.NET CODE
Protected Sub txtUserName_TextChanged(sender As Object, e As EventArgs)
 If txtUserName.Text <> String.Empty Then
  Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
  Dim strSelect As String = "SELECT COUNT(*) FROM Users WHERE Username = @Username"
  Dim con As New SqlConnection(strConnection)
  Dim cmd As New SqlCommand(strSelect, con)

  Dim username As New SqlParameter("@Username", SqlDbType.VarChar)
  username.Value = txtUserName.Text.Trim().ToString()
  cmd.Parameters.Add(username)
  con.Open()
  Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
  con.Close()

  If result >= 1 Then
   imgUser.ImageUrl = "unavailable.png"
   imgUser.Visible = True
   lblUser.Text = "Username not available"
   lblUser.ForeColor = System.Drawing.Color.Red
  Else
   imgUser.ImageUrl = "tick.png"
   imgUser.Visible = True
   lblUser.Text = "Available"
   lblUser.ForeColor = System.Drawing.Color.Green
  End If
 End If
End Sub

Similarly we can check email availability by writing following code in TextChanged Event of email textbox

protected void txtEmail_TextChanged(object sender, EventArgs e)
    {
        if (txtEmail.Text != string.Empty)
        {
            string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string strSelect = "SELECT COUNT(*) FROM Users WHERE Email = @Email";
            SqlConnection con = new SqlConnection(strConnection);
            SqlCommand cmd = new SqlCommand(strSelect, con);
            cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim().ToString());

            con.Open();
            int result = (Int32)cmd.ExecuteScalar();
            con.Close();

            if (result >= 1)
            {
                imgEmail.ImageUrl = "unavailable.png";
                imgEmail.Visible = true;
                lblEmail.Text = "Email already registered";
                lblEmail.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                imgEmail.ImageUrl = "tick.png";
                imgEmail.Visible = true;
                lblEmail.Text = "Available";
                lblEmail.ForeColor = System.Drawing.Color.Green;
            }
        }
    }



Download Sample Code


0

SqlCommand ExecuteXmlReader C# VB.NET Asp.Net

SqlCommand ExecuteXmlReader Method in Asp.Net Using C# And VB.Net

In this post i'm explaining how to use ExecuteXmlReader method of SqlCommand in asp.net.

You may also read how to use ExecuteNonQuery, ExecuteReader and ExecuteScalar Methods of SqlCommand in Asp.Net.

SqlCommand EcecuteXmlReader Method
ExecuteXmlReader method executes the command and builds XmlReader.

For ExecuteXmlReader method to work with fetching database records we need to use FOR XML AUTO clause in sql query.


C# CODE
string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT Username,Password FROM Users FOR XML AUTO";
        
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand(strSelect, con);
        
        con.Open();
        XmlReader reader = cmd.ExecuteXmlReader();
        reader.Read();
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        doc.Save("test.xml");
        reader.Close();
        con.Close();

VB.NET CODE
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim strSelect As String = "SELECT Username,Password FROM Users FOR XML AUTO"

Dim con As New SqlConnection(strConnection)
Dim cmd As New SqlCommand(strSelect, con)

con.Open()
Dim reader As XmlReader = cmd.ExecuteXmlReader()
reader.Read()
Dim doc As New XmlDocument()
doc.Load(reader)
doc.Save("test.xml")
reader.Close()
con.Close()



0

ExecuteScalar Example In Asp.Net C# VB.NET

SqlCommand ExecuteScalar Method Example in Asp.Net Using C# and VB.Net

In this example i'mexplaining when and how to use SqlCommand ExecuteScalar method in asp.net.

You may also read how to use other SqlCommand Methods like ExecuteNonQuery , ExecuteReader and ExecuteXmlReader in Asp.Net.

SqlCommand ExecuteScalar Method
ExecuteScalar Method Executes the query and returns the first column of first row in result set returned by query, other columns and rows are ignored by this method.


It is best used for retrieving a single value eg record count, max,min,sum or getting the identity values of inserted record from database.

C# CODE
string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT COUNT(*) FROM Users WHERE Username = @Username AND Password = @Password";
        
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strSelect;

        SqlParameter username = new SqlParameter("@Username", SqlDbType.VarChar, 50);
        username.Value = txtUserName.Text.Trim().ToString();
        cmd.Parameters.Add(username);

        SqlParameter password = new SqlParameter("@Password", SqlDbType.VarChar, 50);
        password.Value = txtPassword.Text.Trim().ToString();
        cmd.Parameters.Add(password);

        con.Open();
        int result = (Int32)cmd.ExecuteScalar();
        con.Close();

        if (result >= 1)
            Response.Redirect("Default.aspx");
        else
            lblMsg.Text = "Incorrect Username or Password";

VB.NET CODE
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim strSelect As String = "SELECT COUNT(*) FROM Users WHERE Username = @Username AND Password = @Password"

Dim con As New SqlConnection(strConnection)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = strSelect

Dim username As New SqlParameter("@Username", SqlDbType.VarChar, 50)
username.Value = txtUserName.Text.Trim().ToString()
cmd.Parameters.Add(username)

Dim password As New SqlParameter("@Password", SqlDbType.VarChar, 50)
password.Value = txtPassword.Text.Trim().ToString()
cmd.Parameters.Add(password)

con.Open()
Dim result As Integer = DirectCast(cmd.ExecuteScalar(), Int32)
con.Close()

If result >= 1 Then
 Response.Redirect("Default.aspx")
Else
 lblMsg.Text = "Incorrect Username or Password"
End If

To retrieve Identity of inserted record we can write code like mentined below

string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strInsert = "INSERT INTO Users (Username,Password) VALUES (@Username,@Password);"
                          + "SELECT CAST(scope_identity() AS int)";
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand(strInsert, con);
        
        SqlParameter username = new SqlParameter("@Username", SqlDbType.VarChar, 50);
        username.Value = txtUserName.Text.Trim().ToString();
        cmd.Parameters.Add(username);

        SqlParameter password = new SqlParameter("@Password", SqlDbType.VarChar, 50);
        password.Value = txtPassword.Text.Trim().ToString();
        cmd.Parameters.Add(password);

        con.Open();
        int identity = (Int32)cmd.ExecuteScalar();
        con.Close();



0

ExecuteReader Example Asp.Net C# VB.NET

SqlCommand ExecuteReader Method Example in Asp.Net Using C# And Vb.Net

In this example i'm explaining where and how to use ExecuteReader Method of SqlCommand in asp.net using C# and VB.NET.

You may also read ExecuteNonQuery , ExecuteScalar , ExecuteXmlReader methods of SqlCommand in asp.net.

ExecuteReader Method
ExecuteReader Execute the command and builds or populate the SqlDataReader object.

It is used for accessing data when query returns a set of records for display or navigation purpose.

It provides a forward only, read only connected recordset which means it needs open sqlconnection untill sqldatareader is open.


Common usage of SqlDataReader and ExecuteReader Method can be populating a dropdownlist or listbox or retrieving binary files from database.

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT Username FROM Users";

        //Create SQL Connection And SQLCommand
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strSelect;

        con.Open();
        SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            while (dReader.Read())
            {
                ddlUsers.Items.Add(dReader["Username"].ToString());
            }
        dReader.Close();
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim strSelect As String = "SELECT Username FROM Users"

 'Create SQL Connection And SQLCommand
 Dim con As New SqlConnection(strConnection)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = strSelect

 con.Open()
 Dim dReader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
 While dReader.Read()
  ddlUsers.Items.Add(dReader("Username").ToString())
 End While
 dReader.Close()
End Sub

Hope this helps.