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

Saturday, April 27, 2013

Sql Server: How to copy a table?


This is the simplest way to copy a table into another (new) table in the same SQL Server database. This way of copying does not copy constraints and indexes.



select * into [destination table] from [source table]
Example:
Select * into employee_backup from employee
We can also select only a few columns into the destination table like below

select col1, col2, col3 into [destination table]from [source table]
Example:
Select empId, empFirstName, empLastName, emgAge into employee_backup from employee
Use this to copy only the structure of the source table.

select * into [destination table] from [source table] where 1 = 2
Example:
select * into employee_backup from employee where 1=2
Use this to copy a table across two database in the same Sql Server.





select * into [destination database.dbo.destination table] from [source database.dbo.source table]
Example:
select * into Mydatabase2.dbo.employee_backup
from mydatabase1.dbo.employee

Use this to copy a table across two database in the same Sql Server.

select * into [destination database.dbo.destination table]
from [source database.dbo.source table]
 
Example:
select * into Mydatabase2.dbo.employee_backup
from mydatabase1.dbo.employee

Wednesday, April 10, 2013

NUMBER VALIDATION IN VB.NET

How to give number validate in textbox
take keypress event of textbox

Private Sub Txtqty_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Txtqty.KeyPress
Dim i As String = e.KeyChar.ToString
If i = " " Then
Else
If IsNumeric(i) Then
Else
e.Handled = True
MessageBox.Show("Enter valid Number")
End If
End If
End Sub

Tuesday, April 9, 2013

How To Store and retrive ConnectionString from app.config file in vb.net project

[?xmlversion="1.0"encoding="utf-8"?]
[configuration]
[connectionStrings]
[addname="MyDatabase"connectionString="Data Source=server;Initial Catalog=database;
User ID=userid;Password=password"providerName="System.Data.SqlClient"/][/connectionStrings]
[appSettings>[addkey="SomeSetting"value="Value1"/]
[addkey="SomeOtherSetting"value="Value2"/]
[/appSettings]
[/configuration] To access the connection string  you use this code:

Dim myConnString AsString = ConfigurationManager.ConnectionStrings("MyDatabase")
Be sure to add a reference to System.Configuration.dll and add Imports System.Configuration to your code.

Multi-Statement Transactions with Rollback Statement

Begin Tran
insert into usertest(user1)values('sandeep')
insert into usertest1(name)values('lko')
insert into usertest2(fname)values('delhi')
if @@rowcount =1
commit Tran
else
Rollback Tran

Monday, April 8, 2013

SQL String Functions > Concatenate


SQL Server:
SELECT region_name + ' ' + store_name FROM Geography
WHERE store_name = 'Boston';



Table Geography

region_namestore_name
EastBoston
EastNew York
WestLos Angeles
WestSan Diego

Result:
'East Boston'

Sunday, April 7, 2013

Generating Random Numbers

Double-click on the button to write its code.
Type in this code:
Private Sub Cmdrandom_Click()
For i = 0 To 9
Randomize
Txtrandom.Text = Format(((Rnd(i) * 100) + 1), "0")
Next i
End Sub

Friday, April 5, 2013

Java Script for Confirm Box or (yes/no) box

Look At :-
[input id="Button3" onclick="return confirm('Are You Sure?');" type="button" value="button" />]
Eg.

Sending Email From Your Gmail Account in vb.net

Use these namespace and add function to your event on which you want to send email.
*****************************************************************
Imports System.Web
Imports System.Net
Imports System.Net.Mail

Public Function sndmail()
Try

 Dim client As New SmtpClient()
               Dim sendTo As New MailAddress("email of other person")
                Dim from As MailAddress = New MailAddress("youremail")
                Dim message As New MailMessage(from, sendTo)
                message.IsBodyHtml = True
                message.Subject = "Mail subject"
                message.IsBodyHtml = True
                Dim st As String = "Your Mail Body "              
                message.Body = st
                message.IsBodyHtml = True
                Dim basicAuthenticationInfo As New System.Net.NetworkCredential("yourfullemail", "password")
                client.Host = "smtp.gmail.com"
                client.UseDefaultCredentials = False
                client.Credentials = basicAuthenticationInfo
                client.EnableSsl = True
                client.Send(message)

         Catch ex As Exception
            Response.Write("")
        End Try
End Function

******************************************************************

Print A Web Page Javascript

It is just a small function name window.print() you need to call on a button click:-
[input type="button" name="Print" value="Print" onclick="window.print();" /]

Reset All Text Box in windows Form

Public Sub ClearTextBox(ByVal root As Control)
        For Each ctrl As Control In root.Controls
            ClearTextBox(ctrl)
            If TypeOf ctrl Is TextBox Then
                CType(ctrl, TextBox).Text = String.Empty
            End If
        Next ctrl



write the
 ClearTextBox(Me)
under click on reset button

Tuesday, February 19, 2013

Delete Data in Grid View



Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Partial Class admin_student
    Inherits System.Web.UI.Page
    Public cn As SqlConnection
    Public da As SqlDataAdapter


  Public Function fillgrid()
        cn = New SqlConnection("Data Source=;Initial Catalog=;User ID=;Password=")
        da = New SqlDataAdapter("select * from s_reg", cn)
        ds = New DataSet()
        da.Fill(ds)
        GridView1.DataSource = ds
        GridView1.DataBind()
    End Function
    Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
        cn = New SqlConnection("Data Source=;Initial Catalog=;User ID=;Password=")
        da = New SqlDataAdapter("select * from  s_reg", cn)
        Dim cmd As SqlCommandBuilder = New SqlCommandBuilder(da)
        ds = New DataSet
        da.Fill(ds)
        ds.Tables(0).Rows(e.RowIndex).Delete()
        da.Update(ds)
        GridView1.DataSource = ds
        GridView1.DataBind()
    End Sub



Thursday, June 7, 2012

Message Box In Vb.net

Examples of MessageBox.Show in Windows FormsPublic Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load
 '
 ' First show a single-argument dialog box with MessageBox.Show.
 '
 MessageBox.Show("Dot Net Perls is awesome.")
 '
 ' Show a two-argument dialog box with this method.
 '
 MessageBox.Show("Dot Net Perls is awesome.", _
   "Important Message")
 '
 ' Use a three-argument dialog box with MessageBox.Show.
 ' ... Also store the result value in a variable slot.
 '
 Dim result1 As DialogResult = MessageBox.Show("Is Dot Net Perls awesome?", _
            "Important Question", _
            MessageBoxButtons.YesNo)
 '
 ' Use four parameters with the method.
 ' ... Use the YesNoCancel enumerated constant and the Question icon.
 '
 Dim result2 As DialogResult = MessageBox.Show("Is Dot Net Perls awesome?", _
            "Important Query", _
            MessageBoxButtons.YesNoCancel, _
            MessageBoxIcon.Question)
 '
 ' Use five arguments on the method.
 ' ... This asks a question and you can test the result using the variable.
 '
 Dim result3 As DialogResult = MessageBox.Show("Is Visual Basic awesome?", _
     "The Question", _
     MessageBoxButtons.YesNoCancel, _
     MessageBoxIcon.Question, _
     MessageBoxDefaultButton.Button2)
 '
 ' Use if-statement with dialog result.
 '
 If result1 = DialogResult.Yes And _
     result2 = DialogResult.Yes And _
     result3 = DialogResult.No Then
     MessageBox.Show("You answered yes, yes and no.") ' Another dialog.
 End If
 '
 ' Use MessageBox.Show overload that has seven arguments.
 '
 MessageBox.Show("Dot Net Perls is the best.", _
     "Critical Warning", _
     MessageBoxButtons.OKCancel, _
     MessageBoxIcon.Warning, _
     MessageBoxDefaultButton.Button1, _
     MessageBoxOptions.RightAlign, _
     True)
 '
 ' Show a dialog box with a single button.
 '
 MessageBox.Show("Dot Net Perls is super.", _
     "Important Note", _
     MessageBoxButtons.OK, _
     MessageBoxIcon.Exclamation, _
     MessageBoxDefaultButton.Button1)
    End Sub
End Class

Monday, May 21, 2012

Rounded-Corners for Table


 .rounded-corners
   {
     -moz-border-radius: 20px;
    -webkit-border-radius: 20px;
    -khtml-border-radius: 20px;
    border-radius: 20px;
    background:#CC0000;
    width :40%;
    }
OR
write In table Tag
style="border-radius:15px"