Thursday, May 30, 2013

System.Data.SQLClient ,System.Data.OledbClient ,System.Data.ODBCClient

System.Data.SQLClient

Can only be used for connecting to SQL Server 2000 and later. But you will get optimal performance when connecting to those databases.

System.Data.OledbClient

Can be used to connected to SQL 6.5

OLEDBClient gives you ability to connect to other database like ORALCE or Access. But for working with SQL Server you will get better performance using SQLClient.

Note: For connecting to ORALCE Microsoft also has ORACLEClient.

System.Data.ODBCClient- provides connection to legacy databases ( e.g. MS Access 97) using ODBC drivers.

Wednesday, May 29, 2013

Read txt File in RichtextBox

 Private Sub Label2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label2.Click
        'Specify file
        Dim myfile As String = "C:\test.txt"
        'Check if file exists
        If System.IO.File.Exists(myfile) = True  Then
            'Read the file
            Dim objReader As New System.IO.StreamReader(myfile)
            'Save file contents to textbox
            RichTextBox1.Text = objReader.ReadToEnd
            objReader.Close()
        Else
            MsgBox("File not found!")
        End If
    End Sub

Monday, May 27, 2013

send mail in windows application using vb.net

Try
            Dim msg As New System.Net.Mail.MailMessage()
            'msg.[To].Add("vinay.shukla88@gmail.com")
            'msg.[Bcc].Add("jitendra.srivastava555@gmail.com")
            msg.[To].Add(TextBox3.Text)
            msg.[Bcc].Add(TextBox4.Text)
            msg.Subject = TextBox1.Text
            msg.Body = TextBox2.Text
            msg.IsBodyHtml = False
            Dim SMPclint As New SmtpClient()
            SMPclint.Host = "smtp.gmail.com"
            SMPclint.EnableSsl = True
            Dim NetCry As New NetworkCredential()
            NetCry.UserName = "sandeepyadav.bca@gmail.com"
            NetCry.Password = "pwd"
            SMPclint.UseDefaultCredentials = True
            SMPclint.Credentials = NetCry
            Dim fromMailAddr As New MailAddress("sandeepyadav.bca@gmail.com", "")
            msg.From = fromMailAddr
            SMPclint.Port = 587
            SMPclint.Send(msg)
            MessageBox.Show("Message Sent")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

Monday, May 13, 2013

Multicolor RichTextBox


RichTextBox1.Text = "This is black "
        ' Move the insertion point to the end of the line
        RichTextBox1.Select(RichTextBox1.TextLength, 0)
        ' Set the formatting and insert the second snippet of text
        RichTextBox1.SelectionFont = New Font(RichTextBox1.Font, FontStyle.Bold)
        RichTextBox1.SelectionColor = Color.Green
        RichTextBox1.AppendText("BOLD GREEN")
        '' Revert the formatting back to the defaults, and add the third snippet of text
        RichTextBox1.SelectionFont = RichTextBox1.Font
        RichTextBox1.SelectionColor = RichTextBox1.ForeColor
        RichTextBox1.AppendText(" black again")

Sunday, May 12, 2013

Getting Button Name And Text on Mouse Click


Private Sub btnNon_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)Handles Emergency.Click
Dim buttonName As String = ""
If TypeOf sender Is Button Then
buttonName = DirectCast(sender, Button).Name
MessageBox.Show(buttonName)
End If

For  Getting Text :-
 buttonName = (CType(sender, Button).Text)

Thursday, May 9, 2013

Open Word file on Button Click Vb.Net

Public Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
     Dim oWord As Word.Application
        Dim oDoc As Word.Document
        Dim oTable As Word.Table
        Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
        Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
        Dim oRng As Word.Range
        Dim oShape As Word.InlineShape
        Dim oChart As Object
        Dim Pos As Double
        'Start Word and open the document template.
        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oDoc = oWord.Documents.Add
        'Insert a paragraph at the beginning of the document.
        oPara1 = oDoc.Content.Paragraphs.Add
        oPara1.Range.Text = "Heading 1--Sandeep Kumar Yadav"
        oPara1.Range.Font.Bold = True
        oPara1.Format.SpaceAfter = 24    '24 pt spacing after paragraph.
        oPara1.Range.InsertParagraphAfter()
        'Insert a paragraph at the end of the document.
        '** \endofdoc is a predefined bookmark.
        oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
        oPara2.Range.Text = "Heading 2-- M.Tech"
        oPara2.Format.SpaceAfter = 6
        oPara2.Range.InsertParagraphAfter()
        'Insert another paragraph.
        oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
        oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"
        oPara3.Range.Font.Bold = False
        oPara3.Format.SpaceAfter = 24
        oPara3.Range.InsertParagraphAfter()
        'Insert a 3 x 5 table, fill it with data, and make the first row
        'bold and italic.
        Dim r As Integer, c As Integer
        oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 3, 5)
        oTable.Range.ParagraphFormat.SpaceAfter = 6
        For r = 1 To 3
            For c = 1 To 5
                oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
            Next
        Next
        oTable.Rows.Item(1).Range.Font.Bold = True
        oTable.Rows.Item(1).Range.Font.Italic = True
        'Add some text after the table.
        'oTable.Range.InsertParagraphAfter()
        oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
        oPara4.Range.InsertParagraphBefore()
        oPara4.Range.Text = "And here's another table:"
        oPara4.Format.SpaceAfter = 24
        oPara4.Range.InsertParagraphAfter()
        'Insert a 5 x 2 table, fill it with data, and change the column widths.
        oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\endofdoc").Range, 5, 2)
        oTable.Range.ParagraphFormat.SpaceAfter = 6
        For r = 1 To 5
            For c = 1 To 2
                oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
            Next
        Next
        oTable.Columns.Item(1).Width = oWord.InchesToPoints(2)   'Change width of columns 1 & 2
        oTable.Columns.Item(2).Width = oWord.InchesToPoints(3)
        'Keep inserting text. When you get to 7 inches from top of the
        'document, insert a hard page break.
        Pos = oWord.InchesToPoints(7)
        oDoc.Bookmarks.Item("\endofdoc").Range.InsertParagraphAfter()
        Do
            oRng = oDoc.Bookmarks.Item("\endofdoc").Range
            oRng.ParagraphFormat.SpaceAfter = 6
            oRng.InsertAfter("A line of text")
            oRng.InsertParagraphAfter()
        Loop While Pos >= oRng.Information(Word.WdInformation.wdVerticalPositionRelativeToPage)
        oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
        oRng.InsertBreak(Word.WdBreakType.wdPageBreak)
        oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
        oRng.InsertAfter("We're now on page 2. Here's my chart:")
        oRng.InsertParagraphAfter()
        'Insert a chart and change the chart.
        oShape = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddOLEObject( _
            ClassType:="MSGraph.Chart.8", FileName _
            :="", LinkToFile:=False, DisplayAsIcon:=False)
        oChart = oShape.OLEFormat.Object
        oChart.charttype = 4 'xlLine = 4
        oChart.Application.Update()
        oChart.Application.Quit()
        'If desired, you can proceed from here using the Microsoft Graph
        'Object model on the oChart object to make additional changes to the
        'chart.
        oShape.Width = oWord.InchesToPoints(6.25)
        oShape.Height = oWord.InchesToPoints(3.57)
        'Add text after the chart.
        oRng = oDoc.Bookmarks.Item("\endofdoc").Range
        oRng.InsertParagraphAfter()
        oRng.InsertAfter("THE END.")
        'All done. Close this form.
        oWord.ActiveDocument.SaveAs("C:\Documents and Settings\CLIENT4\My Documents\word\Log.doc")
        Me.Close()   

    End Sub

Tuesday, May 7, 2013

How to create a new folder in VB.net

microsoft scripting runtime 
'Import namespace so you can manipulate files and folders
Imports System.IO
 
Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Button1.Click
        ' Check if folder exists, if not: create it
        If Not Directory.Exists("C:\New Folder") Then
            Directory.CreateDirectory("C:\New Folder")
            ' Folder created message
            MessageBox.Show("Folder created!", "Info", MessageBoxButtons.OK, 
MessageBoxIcon.Information)
        Else
            ' Folder already exists
            MessageBox.Show("Folder already exists!", "Info", MessageBoxButtons.OK, 
MessageBoxIcon.Stop)
        End If
    End Sub
 
End Class

Saturday, May 4, 2013

Crystal Reports In Windows Forms With Parameters

In this example i am explaining how to create Crystal Reports In Winforms Or Windows Forms Application With Parameters from user to filter report using C#.NET and VB.NET


Crystal Reports In Winforms Or Windows Forms Application With Parameters
For this i have created two tables in database named Employees and Projects and fetching data from both tables

I've grouped results by Department name using group expert in crystal reports and put a dropdown on the form to select project name to display related report.

Employee table schema

ID    int  
FirstName    varchar(50)
LastName    varchar(50)   
Department    varchar(50)   
ProjectID    numeric(18, 0)  
Expenses    money   


Projects table schema 

ProjectID    numeric(18, 0)   
ProjectName    varchar(50)  









Create a new project in VS and go to solution explorer and add new item > crystal report.
Select Blank report option from the wizard window

 
Now click on CrystalReports menu and select DataBase Expert 
Now in next window expand Create new connection section and OLEDB(ADO) and in next window select SQL Native Client

Enter you SQL Server name , username and password , select database name from the dropdown and click on ok
In next window expand to find your tables and add them in right pane
Click OK to finish

Now Right Click on Group Name Fields in Field Explorer and Select Group Expert.
In group expert box select the field on which you want data to be grouped.
 
  
Design your report by dragging the fields in section3 (Details) 
my design look like this  
In the form add a combobox and drag and drop CrystalReport Viewer from toobox. click on smart tag and choose the report we created earlier (CrystalReport1.rpt) 
Form look like this 
When we build and rum this report , it asks for Database login username and password , we need to provide database username and password in code behind.
 we need to write code in code behind to filter report based on user selected value or value provided by user .
VB.NET code behind
//Code to populate dropdown
//Fill dropdown in form_Load event by calling 
//function written below
private void FillDropDown()
{
 SqlConnection con = new SqlConnection
       (ConfigurationManager.AppSettings["myConnection"]);
 SqlCommand cmd = new SqlCommand
("Select distinct ProjectID,ProjectName from Projects", con);
 con.Open();
 DataSet objDs = new DataSet();
 SqlDataAdapter dAdapter = new SqlDataAdapter();
 dAdapter.SelectCommand = cmd;
 dAdapter.Fill(objDs);
 cmbMonth.DataSource = objDs.Tables[0];
 cmbMonth.DisplayMember = "ProjectName";
 cmbMonth.ValueMember = "ProjectID";
 cmbMonth.SelectedIndex = 0;
}
private void cmbMonth_SelectedIndexChanged
              (object sender, EventArgs e)
{
      //Create object of report 
CrystalReport1 objReport = new CrystalReport1();

    //set database login information
objReport.SetDatabaseLogon
    ("amit", "password", @"AVDHESH\SQLEXPRESS", "TestDB");

//write formula to pass parameters to report 
crystalReportViewer1.SelectionFormula 
    ="{Projects.ProjectID} =" +cmbMonth.SelectedIndex;
crystalReportViewer1.ReportSource = objReport;
}
      
 

Friday, May 3, 2013

When occer these type of error--- operator '=' is not defined for type 'dbnull' and string


When occer these type of error--- operator '=' is not defined for type 'dbnull' and string
                If DataGridView1.Rows(i).Cells("victim_name").Value = p Then

Then to use Convert.ToString
  If Convert.ToString(DataGridView1.Rows(i).Cells("victim_name").Value) = p Then