Thursday, June 16, 2011

Add CheckBox DataGridView Header

Add this class
________________________
Public Class DGVColumnHeader
Inherits DataGridViewColumnHeaderCell
Private CheckBoxRegion As Rectangle
Private m_checkAll As Boolean = False

Protected Overrides Sub Paint(ByVal graphics As Graphics, ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, ByVal rowIndex As Integer, ByVal dataGridViewElementState As DataGridViewElementStates, ByVal value As Object, _
ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, ByVal paintParts As DataGridViewPaintParts)

MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, _
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)

graphics.FillRectangle(New SolidBrush(cellStyle.BackColor), cellBounds)

CheckBoxRegion = New Rectangle(cellBounds.Location.X + 1, cellBounds.Location.Y + 2, 25, cellBounds.Size.Height - 4)


If Me.m_checkAll Then
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked)
Else
ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal)
End If

Dim normalRegion As New Rectangle(cellBounds.Location.X + 1 + 25, cellBounds.Location.Y, cellBounds.Size.Width - 26, cellBounds.Size.Height)

graphics.DrawString(value.ToString(), cellStyle.Font, New SolidBrush(cellStyle.ForeColor), normalRegion)
End Sub

Protected Overrides Sub OnMouseClick(ByVal e As DataGridViewCellMouseEventArgs)
'Convert the CheckBoxRegion
Dim rec As New Rectangle(New Point(0, 0), Me.CheckBoxRegion.Size)
Me.m_checkAll = Not Me.m_checkAll
If rec.Contains(e.Location) Then
Me.DataGridView.Invalidate()
End If
MyBase.OnMouseClick(e)
End Sub

Public Property CheckAll() As Boolean
Get
Return Me.m_checkAll
End Get
Set(ByVal value As Boolean)
Me.m_checkAll = value
End Set
End Property
End Class
_____________________

On Your code write
_________________
For i As Integer = 0 To grdViev.Columns.Count - 1
Dim DGV As New DGVColumnHeader
grdViev.Columns(i).HeaderCell = DGV

Next

Wednesday, June 15, 2011

Open Word document in vb.net( desktop application )

Place your doc file under bin/debug/

Paste the following code

Dim objword As Object
objword = CreateObject("Word.Application")
objword.Visible = True
objword.Documents.Open(Application.StartupPath + "/help.doc")

Saturday, June 11, 2011

Maintaining State of CheckBoxes While Paging in a GridView Control

CREATE THIS AS GLOBAL

public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex";

private void RePopulateCheckBoxes()
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;

IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;

if (SelectedCustomersIndex != null)
{
if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
{
chkBox.Checked = true;
}
}
}
}

private List SelectedCustomersIndex
{
get
{
if (ViewState[SELECTED_CUSTOMERS_INDEX] == null)
{
ViewState[SELECTED_CUSTOMERS_INDEX] = new List();
}

return (List)ViewState[SELECTED_CUSTOMERS_INDEX];
}
}

private void RemoveRowIndex(int index)
{
SelectedCustomersIndex.Remove(index);
}

private void PersistRowIndex(int index)
{
if (!SelectedCustomersIndex.Exists(i => i == index))
{
SelectedCustomersIndex.Add(index);
}
}


WRITE THIS IN GRIDVIEW PAGEINDEXCHANGING

protected void grdInvitee_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
foreach (GridViewRow row in grdInvitee.Rows)
{
var chkBox = row.FindControl("CheckBox1") as CheckBox;

IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;

if (chkBox.Checked)
{
PersistRowIndex(container.DataItemIndex);
}
else
{
RemoveRowIndex(container.DataItemIndex);
}
}

grdInvitee.PageIndex = e.NewPageIndex;
PopulateInviteeGrid();
RePopulateCheckBoxes();

}

Tuesday, June 7, 2011

Split Words With Coma and sapace

Dim s As String = txtsearch.Text.ToString()
Dim s1 As String = s
' Split string based on spaces
Dim words As String() = s.Split(New Char() {","c})
s1 = s1.Replace(",", " ")
Dim words1 As String() = s1.Split(New Char() {" "c})

' Use For Each loop over words and display them
Dim word As String
For Each word In words
Console.WriteLine(word)
arrSTR.Add(word)
Next

For Each word In words1
Console.WriteLine(word)
arrSTR.Add(word)
Next

Confirm Delete message in grid cell click , asp.net

Add a TemplateField in your grid column and paste the following code and bind.


Saturday, June 4, 2011

Java Script Alert in C#

ADD A CLASS IN APP_CODE AND REPLACE WITH FOLLOWING CODE.RENAME THE CLASS FILE WITH Alert.cs


using System.Web;
using System.Text;
using System.Web.UI;

///
/// A JavaScript alert
///

public static class Alert
{

///
/// Shows a client-side JavaScript alert in the browser.
///

/// The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("'", "\\'");
string script = "";

// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;

// Checks if the handler is a Page and that the script isn't allready on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}

}

Get Browser Version in C# Asp.Net

if (!(IsPostBack))
{
if (Request.Browser.Browser == "IE")
{
if (Request.Browser.MajorVersion <= 6)
{
/ /Your Code

}
}
}

Wednesday, June 1, 2011

How to Print in ASP.NET 3.5

One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows.
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
public class PrintHelper
{
public PrintHelper()
{
}

public void PrintWebControl(Control ctrl)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;

HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("");
HttpContext.Current.Response.End();
}

Convert LINQ to System.Data.Datatable

using System.Reflection;

public DataTable LINQToDataTable(System.Collections.Generic.IEnumerable varlist)
{
DataTable dtReturn = new DataTable();

// column names
PropertyInfo[] oProps = null;

if (varlist == null) return dtReturn;

foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;

if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}

dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}

DataRow dr = dtReturn.NewRow();

foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}

dtReturn.Rows.Add(dr);
}
return dtReturn;
}

Send mail with attachment in vb.net for web

Private Sub sendmailwithattachment(ByVal [To] As String, ByVal subject As String, ByVal body As String, ByVal attach As FileUpload)
Try
Dim loginInfo As New NetworkCredential("-your mail id -", "-password-")
Dim msg As New System.Net.Mail.MailMessage()
msg.From = New MailAddress("-your mail id -")
msg.[To].Add(New MailAddress([To]))
msg.Subject = subject
msg.Body = body
msg.IsBodyHtml = True

Dim fileName As String = Path.GetFileName(attach.PostedFile.FileName)
Dim myAttachment As New Attachment(attach.FileContent, fileName)
msg.Attachments.Add(myAttachment)


Dim client As New SmtpClient("smtp.gmail.com")
client.EnableSsl = True
client.UseDefaultCredentials = False
client.Credentials = loginInfo
client.Send(msg)
lblMsg.Text = "mail send"
Catch ex As Exception
lblMsg.Text = "mail sending failed"
Return
End Try
End Sub