Friday, March 20, 2009
Detect SHIFT, ALT, CTRL & character key example
document.onkeydown = KeyDownHandler;
document.onkeyup = KeyUpHandler;
var CTRL = false;
var SHIFT = false;
var ALT = false;
var CHAR_CODE = -1;
function KeyDownHandler(e)
{
var x = '';
if (document.all)
{
var evnt = window.event;
x = evnt.keyCode;
}
else
{
x = e.keyCode;
}
DetectKeys(x, true);
ShowReport();
}
function KeyUpHandler(e)
{
var x = '';
if (document.all)
{
var evnt = window.event;
x = evnt.keyCode;
}
else
{
x = e.keyCode;
}
DetectKeys(x, false);
ShowReport();
}
function DetectKeys(KeyCode, IsKeyDown)
{
if (KeyCode == '16')
{
SHIFT = IsKeyDown;
}
else if (KeyCode == '17')
{
CTRL = IsKeyDown;
}
else if (KeyCode == '18')
{
ALT = IsKeyDown;
}
else
{
if(IsKeyDown)
CHAR_CODE = KeyCode;
else
CHAR_CODE = -1;
}
}
function ShowReport()
{
var TBReport = document.getElementById("tbReport");
//tbReport is textbox control with id=tbReport
var DIVCtrl = document.getElementById("IsCtrl");
var DIVShift = document.getElementById("IsShift");
var DIVAlt = document.getElementById("IsAlt");
var DIVChar = document.getElementById("IsChar");
document.title = 'SHIFT: ' + SHIFT + ', CTRL: ' + CTRL + ', ALT: ' + ALT + ', Char code is: ' + CHAR_CODE;
TBReport.value = document.title;
if(SHIFT)
DIVShift.style.visibility = "visible";
else
DIVShift.style.visibility = "hidden";
if(ALT)
DIVAlt.style.visibility = "visible";
else
DIVAlt.style.visibility = "hidden";
if(CTRL)
DIVCtrl.style.visibility = "visible";
else
DIVCtrl.style.visibility = "hidden";
}
How to use Repeater Control
For example, DataGrid control is suitable in many scenarios where you wish to display data in a grid like representation for easy understanding. Similarly, if the situation demands for rendering list like data, you can consider using of DataLists and Repeater server controls.
Repeater control is a container control which is template based with no basic rendering of its own. This way, you define layout for the Repeater control by creating different templates based on your needs. You can create different kinds of lists using Repeater control including Table, Comma-separated list and XML formatted list.
Repeater Control Templates
Repeater controls provides different kinds of templates which helps in determining the layout of control's content. Templates generate markup which determine final layout of content.
Repeater control is an iterative control in the sense it loops each record in the DataSource and renders the specified template (ItemTemplate) for each record in the DataSource collection. In addition, before and after processing the data items, the Repeater emits some markup for the header and the footer of the resulting structure
Repeater control supports five templates which are as follows:
ItemTemplate
AlternatingItemTemplate
HeaderTemplate
FooterTemplate
SeparatorTemplate
ItemTemplate: ItemTemplate defines how the each item is rendered from data source collection.
AlternatingItemTemplate: AlternatingItemTemplates define the markup for each Item but for AlternatingItems in DataSource collection like different background color and styles.
HeaderTemplate: HeaderTemplate will emit markup for Header element for DataSource collection
FooterTemplate: FooterTemplate will emit markup for footer element for DataSource collection
SeparatorTemplate: SeparatorTemplate will determine separator element which separates each Item in Item collection. Usually, SeparateTemplate will be
html element or
html element.
DataBinding in Repeater Control
Like any other Data Bound control, Repeater control supports DataSource property which allows you to bind any valid DataSource like sqlDataSource, XML file or any datasets which implements ICollection, IEnumerable or IListSource Interfaces.
The data in DataSource is bound to Repeater using its DataBind Method. Once the data is bound, the format of each data item is defined by a template like ItemTemplate.
Adding Repeater server control to ASP.NET page
Add any Data Source control to the page such as sqlDataSource or AccessDataSource. Configure Data Source control such that you specify connection information and perform query.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode] FROM [Customers]">asp:SqlDataSource>
Drag and Drop Repeater control from Data section of the Toolbox onto the page.
<asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server" asp:Repeater>
Set the DataSourceID property of Repeater Control to newly configured sqlDataSource control as shown above.
Add an
Embed HTML markup and Web server controls or HTML server controls to the ItemTemplate to render data at run time
Bind the child controls to data from the query using the Eval data-binding function.
Following example shows how to use Repeater control to display data in a HTML table.
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<table border="1" cellpadding="5" cellspacing="2">
<tr bgcolor="gray">
<td><b>CompanyNameb>
td>
<td><b>Cityb>td>
tr>
HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>
td>
<td>
<%#DataBinder.Eval(Container.DataItem, "City")%>
td>
tr>
ItemTemplate>
<AlternatingItemTemplate >
<tr bgcolor="aqua" >
<td>
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>
td>
<td>
<%#DataBinder.Eval(Container.DataItem, "City")%>
td>
tr>
AlternatingItemTemplate>
<FooterTemplate>
table>
FooterTemplate>
asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode] FROM [Customers]">asp:SqlDataSource>
Repeater Control in action
The Databinder.Eval method uses reflection to parse and evaluate a data-binding expression against an object at run time; in this case the object is our Repeater. So this line of code:
<%#DataBinder.Eval(Container.DataItem, "CompanyName")%>
It will render the contents of the "CompanyName" field for each row in the DataSource Collection.Developing a picture album in ASP.NET
Picture album functionalities
The following functionalities will be implemented and put together so that at the end, we can get a complete photo album management system:
Creating Categories; the images will be classified as per categories: New Year, Picnic, Birthdays etc...
Uploading pictures in a category and writing a memo of that picture.
Displaying the pictures as per category.
You can download sample Picture Album Visual Studio .NET project used in this tutorial.
Database Design
Figure 1. Two tables are defined, Category and Photo, with a foreign key linking them as shown above.
Figure 2. Table schema for Category, with primary key "PKCategoryId". The "Is Identity" property of the primary key is set to "Yes"
Figure 3. Table schema for Photo, with primary key "PKPhotoId" and foreign key "FKCategoryId". Memo can be set to null as well.
The Master Page
We will make use of the Master Page to bring uniformity to the website being developed. It will contain the menu for displaying the categories and also the links to add new photo or photo category.
First, 2 hyperlinks are dropped on the form "Create New Category" and "Upload Photo" and their "Navigate URL" linked to the appropriate pages. Also, it is very important to set their "Causes Validation" property to False.
Then, a data source needs to be bound to it so that all the categories are displayed.
Chose the database and save the connection string in the Web.config file. Next, choose all the fields that are found in the table "Category", which we will use later. We can also choose to sort the list by Title, which makes sense in a way.
Click on "Next" and "Test Query" just to make sure the proper dataset is retrieved.
The Item Template of the Datalist can be altered to get better menu displayed. First of all, the labels in the list need to be replaced by hyperlinks so the user can be redirected to the proper gallery when he/she clicks on a particular category. We can also choose to apply a ToolTip text so the description of the category is displayed whenever the mouse is hovered over the link.
The text of the hyperlink is bound to the Title field of the dataset being returned by query.
The page where the user should be directed is "Main.aspx". Also, to display the pictures in that particular category, a query string which makes use of the field "PKCategoryId" is used.
To display the ToolTip text on that URL, the following code needs to be added in the .aspx file:
ToolTip='<%# Eval("Description") %>'
One last thing that is really important is to get all the changes reflected in the master page (like when adding a new category). The DataList has to be simply refreshed with the datasource. And that is done in the Page_Load event of the Master Page.
' Refresh the datalist
dtlCategory.DataBind()
Adding New Categories
The screen below will be used to input new photo categories.
2 textboxes will be used for providing information about the category. Required Fields validators are also used to ensure that the information is supplied for both the Category Title and description.
So, on the Click_Event of the button to add a new category, the following function will be used. Note that System.Data and System.Data.SqlClient need to be imported.
Private Sub addNewCategory(ByVal strTitle As String, ByVal strDescription As String)
' Variables declaration
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings.Item("ConnectionString").ToString()
Dim sqlConn As New SqlConnection(strConnString)
Dim sqlcmd As New SqlCommand()
' Building the query
Dim sqlQuery_Category As String = "INSERT INTO [Category] VALUES ('{0}', '{1}')"
sqlQuery_Category = sqlQuery_Category.Replace("{0}", strTitle)
sqlQuery_Category = sqlQuery_Category.Replace("{1}", strDescription)
' Retrieving search result
sqlConn.Open()
sqlcmd.Connection = sqlConn
' Adding records to table
sqlcmd.CommandText = sqlQuery_Category
sqlcmd.ExecuteNonQuery()
sqlConn.Close()
End Sub
The parameters strTitle and strDescription are the values obtained from the 2 textboxes.
The snapshot below shows the scenario where a new category (Christmas) was added.
Uploading a picture in a Category
The screen below will be used to upload a photo to a particular category. The flow for uploading a photo:
Select a category from the list
Browse for a photo
Write some comments about the photo
To populate the combo list "Category" is quite simple, as shown in the screenshots below.
Chosing a new data source
Select the table category and columns "PKCategoryId" and "Title". Sort the list by Title
Then select the value and the corresponding text to display in the combo list as follows.
That should be enough in populating the combo list with the categories available.
The "FileUpload" object provided in ASP.NET 2.0 is really useful as it decreases a lot of work as compared to version 1.1. It provides a method called "FileExist" that helps in determining whether the file being browsed really exist on the machine; thus avoiding all sorts of errors.
Also, it is important to give each picture being uploaded a unique name such that if 2 picture of the same name would exist in the uploaded folder, some unexpected behaviour may occur. For that, we will make use of the time stamp, i.e. the time at which the picture is uploaded. In this tutorial, we will call it the GUID รข€“ General Unique Identifier.
' Function to generate a GUID using current date and time
Private Function fnGuid() As String
Dim strGuid As String = ""
Try
With Today
strGuid = .Year & .Month & .Day & Now.Hour & Now.Minute & Now.Second
End With
Catch ex As Exception
Throw ex
End Try
' returning the guid generated
Return strGuid
End Function
We need a place to keep the picture. So, we will create a folder in the solution called "Gallery".
New folder named "Gallery" added in solution
Before uploading a file, we need to check the extension of the file. In our concern, we will only process images (jpg, jpeg and gif). You are free to extend the list! The following code snippet checks for the extensions.
' Returns true if file name has the extension .jpg, .gif, .jpeg
Private Function fnGetPictureExtension(ByVal strPictureName As String) As String
Try
With strPictureName.ToUpper
If .EndsWith(".JPG") Then
Return ".JPG"
ElseIf .EndsWith(".GIF") Then
Return ".GIF"
ElseIf .EndsWith(".JPEG") Then
Return ".JPEG"
End If
End With
Catch ex As Exception
Throw ex
End Try
' Else if has no extension so it returns ""
Return ""
End Function
To save the picture physically in the "Gallery" folder, the following function is used.
' Adds picture to specified folder
Private Sub subAddNewPicture(ByVal FileUploader As FileUpload, ByVal strPictureName As String, ByVal strImgFolder As String)
Dim strImageFolderPath As String
Dim strImagePath As String
Try
' Construct saving path
strImageFolderPath = Path.Combine(Request.PhysicalApplicationPath, strImgFolder)
strImagePath = Path.Combine(strImageFolderPath, strPictureName)
' Upload image
FileUploader.SaveAs(strImagePath)
Catch ex As Exception
Throw ex
End Try
End Sub
The function takes in 3 parameters:
FileUploader, which is the FileUpload control.
strPictureName, which is the name of the picture, which is the GUID + picture extension.
strImgFolder, which is the name of the folder that the image should be stored.
Also, we need a function to store that file name in the database. The following code snippet takes category value from the combo list, the filename and the memo and adds a corresponding record in the database.
Private Sub UpdateGallery(ByVal strCategoryValue As String, ByVal strFileName As String, ByVal strMemo As String)
' Variables declaration
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings.Item("ConnectionString").ToString()
Dim sqlConn As New SqlConnection(strConnString)
Dim sqlcmd As New SqlCommand()
' Building the query
Dim sqlQuery_Photo As String = "INSERT INTO [Photo] VALUES ('{0}', '{1}', '{2}')"
sqlQuery_Photo = sqlQuery_Photo.Replace("{0}", strCategoryValue)
sqlQuery_Photo = sqlQuery_Photo.Replace("{1}", strFileName)
sqlQuery_Photo = sqlQuery_Photo.Replace("{2}", strMemo)
' Retrieving search result
sqlConn.Open()
sqlcmd.Connection = sqlConn
' Adding records to table
sqlcmd.CommandText = sqlQuery_Photo
sqlcmd.ExecuteNonQuery()
sqlConn.Close()
End Sub
So, on the click event of the "Upload" button, the above functions will be used to add the picture to the "Gallery" folder and insert record in database.
Protected Sub btnAddToCategory_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddToCategory.Click
Try
Dim strGuid As String = ""
Dim strPicExtension As String = ""
Dim strFileName As String = ""
' Firstly upload the picture associated with the news
If PhotoUpload.HasFile Then
' Constructs the picture extension
strGuid = fnGuid()
strPicExtension = fnGetPictureExtension(PhotoUpload.FileName)
strFileName = strGuid & strPicExtension
' Add picture to folder
subAddNewPicture(PhotoUpload, strFileName, "Gallery")
' Add the record to the database
UpdateGallery(cmbCategory.SelectedValue, strFileName, txtMemo.Text.Trim())
End If
Catch ex As Exception
Throw ex
End Try
End Sub
The screenshot below illustrates a scenario of uploading the picture.
Displaying the pictures
It is easy job to display the photos. We will use a DataList control for that. The same principle is used to display category list in the left menu.
A new Data List is added in the main page and data source is connected to it.
After choosing the connection string, choose the "Photo" table and check all the fields.
After that, click on the "WHERE" button to display the picture as per category. This is obtained from the query string, as shown below.
The Query field is "Category". Click on the "Add" button. Make sure that the Default Value is "0" in case there is no category added yet. Click on "OK"
Test the SQL command generated by putting the query string as "1". Then, click on the "Finish" button.
Back to the Data List, only the record information is displayed. But, we need to display the picture. So, edit the "Item Template" and put in an Image object. The picture's attribute is then linked with the data retrieved from the data source. The snapshot below shows how this is done.
The expression Eval("Filename", "~\Gallery\{0}") makes sure to link the path of the images, concatenated with the Filename field.
Also, the size of the pictures is set to 100px to 100px. The "RepeatColumns" property of the Data List is modified to 5 and the "Repeat Direction" to Horizontal
We are only seeing the thumbnails, as illustrated in the figure below.
To allow a larger view of the picture to be displayed, some HTML works need to be done. The
<a href='<%# Eval("Filename", "./Gallery/{0}") %>' target="_blank">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px"
ImageUrl='<%# Eval("Filename", "~\Gallery\{0}") %>'
ToolTip='<%# Eval("Memo") %>'
/>
a>
Storing Images to Database and Retrieving to GridView
Creating the File Upload page:
We will start with the default page, from where we will provide the user the functionality to upload the images. Open Default.aspx and switch to design-view. Drag-n-drop controls from the toolbox onto the page to create a similar form:
The Text-Box followed by the Browse button is the HTML File Input control. After adding this control onto the form switch to Source-View and add modify the control's source to include runat="server". This will allow us to use the control as a server control.
In the above page, the controls are as follows:
- fileUpload - To select the file to upload.
- txtTitle - The title of the image.
- btnUpload - On click uploads the selected image.
- lnkView - The View Images link that loads the images from the databases inside a GridView.
- Validation Controls - The Required Field Validation Controls in order to make sure that Title and File are selected.
Let us suppose that the Database File already exists. If not then add one now by right-clicking the Project and clicking on Add Item. Select Database and name it imgDB.mdf. The database will contain one table which is as follows:
Switch to the code-behind class of Default.aspx and add a button click event handler for btnUpload.
Protected Sub btnUpload_Click(..., ...) Handles btnUpload.Click
Dim intLength As Integer
Dim arrContent As Byte()
If fileUpload.PostedFile Is Nothing Then
lblStatus.Text = "No file specified."
Exit Sub
Else
Dim fileName As String = fileUpload.PostedFile.FileName
Dim ext As String = fileName.Substring(fileName.LastIndexOf("."))
ext = ext.ToLower
Dim imgType = fileUpload.PostedFile.ContentType
If ext = ".jpg" Then
ElseIf ext = ".bmp" Then
ElseIf ext = ".gif" Then
ElseIf ext = "jpg" Then
ElseIf ext = "bmp" Then
ElseIf ext = "gif" Then
Else
lblStatus.Text = "Only gif, bmp, or jpg format files supported."
Exit Sub
End If
intLength = Convert.ToInt32(fileUpload.PostedFile.InputStream.Length)
ReDim arrContent(intLength)
fileUpload.PostedFile.InputStream.Read(arrContent, 0, intLength)
If Doc2SQLServer(txtTitle.Text.Trim, arrContent, intLength, imgType) = True Then
lblStatus.Text = "Image uploaded successfully."
Else
lblStatus.Text = "An error occured while uploading Image... Please try again."
End If
End If
End Sub
What this function does is that it grabs the file selected in the File Input control and gets its extension. If the file is of type jpg, bmp, or gif, then it proceeds otherwise it throws an error. This terminates upload if the selected file is not an image of supported format.
After checking the file format, we get the length of the file and create a Byte Array of that same length. This Byte Array will store our file/image for us. Using the InputStream.Read method of fileUpload control, we load the image into the Byte Array.
After having saved the file into the byte array, we call our function Doc2SQLServer to store the file. We pass in the title that was supplied by the user, the byte array (which is our image), the total length, and the type of image.
In the Doc2SQLServer method, we create a connection to our SQL Express database and create an insertion command. After connecting to the database, we execute the query and store our image and its information to the database. Below is the Doc2SQLServer method.
Protected Function Doc2SQLServer(ByVal title As String, ByVal Content As Byte(), ByVal Length As Integer, ByVal strType As String) As Boolean
Try
Dim cnn As Data.SqlClient.SqlConnection
Dim cmd As Data.SqlClient.SqlCommand
Dim param As Data.SqlClient.SqlParameter
Dim strSQL As String
strSQL = "Insert Into tblImage(imgData,imgTitle,imgType,imgLength) Values(@content,@title,@type,@length)"
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"
cnn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand(strSQL, cnn)
param = New Data.SqlClient.SqlParameter("@content", Data.SqlDbType.Image)
param.Value = Content
cmd.Parameters.Add(param)
param = New Data.SqlClient.SqlParameter("@title", Data.SqlDbType.VarChar)
param.Value = title
cmd.Parameters.Add(param)
param = New Data.SqlClient.SqlParameter("@type", Data.SqlDbType.VarChar)
param.Value = strType
cmd.Parameters.Add(param)
param = New Data.SqlClient.SqlParameter("@length", Data.SqlDbType.BigInt)
param.Value = Length
cmd.Parameters.Add(param)
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
The Image Grabber
Next we create a web-page that will grab the image whose id is passed to it as a query string. Right-click the project in solution explorer and add a web-page imgGrab.aspx.Define the page_load method as follows:
Protected Sub Page_Load(...,...) Handles Me.Load
Try
Dim ds As New DataSet
Dim da As SqlClient.SqlDataAdapter
Dim arrContent As Byte()
Dim dr As DataRow
Dim strSql As String
strSql = "Select * from tblImage Where imgId=" & Request.QueryString("ID")
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"
da = New SqlClient.SqlDataAdapter(strSql, connString)
da.Fill(ds)
dr = ds.Tables(0).Rows(0)
arrContent = CType(dr.Item("imgData"), Byte())
Dim conType As String = dr.Item("imgType").ToString()
Response.ContentType = conType
Response.OutputStream.Write(arrContent, 0, dr.Item("imgLength"))
Response.End()
Catch ex As Exception
End Try
End Sub
What this does is quite simple. It gets the image data whose id is passed in and writes it to the web-page. Response.ContentType sets the web-page as an image content holder and when we write the complete byte array to the response stream, we actually get the image.
Loading Images into the GridView Control
A major problem faced by developers is when loading images back into the datagrid or the new gridview control. I myself faced long hours trying to come up with a solution for this, which in the end was a simple procedure.
Create a new-page, Viewer.aspx and add a GridView onto it. (This page is linked from the Default.aspx page via lnkView). Name the GridView imgGrid and click on the small box located at the upper-right corner of the control.
Click on Edit Columns to open the Fields Dialog as shown below.
In this dialog, uncheck "Auto-generate fields" and add two fields; a bound field and an image field. For the bound field set the column header text to Title and the DataField property to imgTitle (This will bind this column to the imgTitle column in the dataset to which we will load our table data). As for the image field, set the caption to Picture and the DataImageUrlField to imgFile. You might think where this imgFile comes from, especially since the database does not contain a column with such a name.
Switch to the code-behind class and create the page_load event as follows:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim ds As New DataSet
Dim da As SqlClient.SqlDataAdapter
Dim strSQL As String
strSQL = "Select imgId,imgTitle from tblImage"
Dim connString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=""|DataDirectory|\imgDB.mdf"";Integrated Security=True;User Instance=True"
da = New SqlClient.SqlDataAdapter(strSQL, connString)
da.Fill(ds)
ds.Tables(0).Columns.Add("imgFile")
For Each tempRow As DataRow In ds.Tables(0).Rows
tempRow.Item("imgFile") = ("imgGrab.aspx?id=" & tempRow.Item("imgID"))
Next
imgGrid.DataSource = ds
imgGrid.DataBind()
End Sub
What this function does is the simple task of grabbing data from the database. It grabs two columns, imgId and imgTitle. What it does afterwards is the key concept... and the few-lines of code that marks the solution to a big problem.
After filling in the dataset, we know that it contains one table, at index 0 of course. We add a custom column "imgFile" to it.
After that, we traverse through each dataRow in the table. And for each row, we make a call to our imgGrab.aspx page with the id from that row. We set this equal to the record for imgFile for that row.
Thus on display of the GridView, for each row being displayed, the imgGrab.aspx web-page is called and the image is displayed in return.
Friday, March 6, 2009
Getting Previous Values of Formula Fields in Crystal Report
Suppose if I want to add balance of a previous record to next like below ,
| Amount | Paid | Balance |
| 1000 | 500 | 500 |
| 1250 | 1000 | 750 (500+250) |
| 500 | 300 | 950 (750+200) |
>> First create a formula field, say: tempBalance
In that write:
shared numberVar x:=0;
x:={@balance} //{@balance} is formula filed which will calculate balance
In @balance write:
shared numberVar x;
{PaymentDetails.Total}-{PaymentDetails.Paid} + x
//In @balance the variable x will get the previous value from @tempBalance . Only we have to declare here as shared numberVar x;
Wednesday, March 4, 2009
Using Word Control in .NET
Download and install dsoframer and restart Visual Studio
If dsoframer control doesn't appear in toolbox , then manually add the toolbox from Com tab.
>> Drag the conttrol to form.
- Displaying Ruler through coding
{
wordCtl.document.ActiveWindow.DisplayRulers = !(wordCtl.document.ActiveWindow.DisplayRulers);
}
catch { }
2. Displaying font Toolbox b
try
{
object novalue = System.Reflection.Missing.Value;
WinWordControl.WinWordControl.wd.Dialogs.Item(Word.WdWordDialog.wdDialogFormatFont).Show(ref novalue);
}
catch (Exception ex) { }
3. Bullets and Numbering
try
{
object novalue = System.Reflection.Missing.Value;
WinWordControl.WinWordControl.wd.Dialogs.Item(Word.WdWordDialog.wdDialogFormatBulletsAndNumbering).Show(ref novalue);
}
catch (Exception ex) { }
4. Spelling and Grammer
try
{
object novalue = System.Reflection.Missing.Value;
WinWordControl.WinWordControl.wd.Dialogs.Item(Word.WdWordDialog.wdDialogToolsOptionsSpellingAndGrammar).Show(ref novalue);
}
catch (Exception ex) { }
5. Insert Table
try
{
object novalue = System.Reflection.Missing.Value;
WinWordControl.WinWordControl.wd.Dialogs.Item(Word.WdWordDialog.wdDialogTableInsertTable).Show(ref novalue);
}
catch (Exception ex) { }
Code for Creating System Wide HotKey
const int MYKEYID1 = 9;
const int MYKEYID2 = 10;
const int MYKEYID3 = 11;
public const int VK_F2 = 0x71; //F2 key
public const int VK_F3 = 0x72; //F3 key
public const int VK_F4 = 0x73; //F4 key
//0x74,0x75...... etc for F5,F6 etc.....
public const int WM_HOTKEY = 0x312;
[DllImport("user32.dll")]
private static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern int UnregisterHotKey(IntPtr hwnd, int id);
protected override void WndProc(ref System.Windows.Forms.Message m)
{
try
{
if (m.Msg == WM_HOTKEY)
{
switch (m.WParam.ToInt32())
{
case MYKEYID1:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
case MYKEYID2:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
case MYKEYID3:
try
{
//do the action
}
catch (Exception ex)
{
}
break;
}
}
base.WndProc(ref m);
//Never Forget This
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//In form Load
try
{
RegisterHotKey(this.Handle, MYKEYID1, MOD_ALT, VK_F2); //Registers F2
RegisterHotKey(this.Handle, MYKEYID2, MOD_ALT, VK_F3); //Registers F3
RegisterHotKey(this.Handle, MYKEYID3, MOD_ALT, VK_F4); //Registers F4
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//In Form Closing==== Don't forget to do this
UnregisterHotKey(this.Handle, MYKEYID1);//Remember to unregister the hotkey
UnregisterHotKey(this.Handle, MYKEYID2); //Remember to unregister the hotkey
UnregisterHotKey(this.Handle, MYKEYID3); //Remember to unregister the hotkey
Function to Clear all ComboBoxes in a form
Dim meuForm As Type = f.GetType()
Dim campos As Reflection.FieldInfo() = meuForm.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
For Each campo As Reflection.FieldInfo In campos
If campo.FieldType.Name.ToLower = "combobox" Then
Dim t As ComboBox = DirectCast(campo.GetValue(f), ComboBox)
t.Text = ""
t.SelectedIndex = -1
End If
Next
End Sub
NOTE: We can clear all controls within this function. Use proper select case to do all action.
Function to Clear all TextBox fields in a form
Dim meuForm As Type = f.GetType()
Dim campos As Reflection.FieldInfo() = meuForm.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
For Each campo As Reflection.FieldInfo In campos
If campo.FieldType.Name.ToLower = "textbox" Then
Dim t As TextBox = DirectCast(campo.GetValue(f), TextBox)
t.Text = ""
End If
Next
End Sub