Monday, October 18, 2010
Import Excel Spreadsheet Data into SQL Server Database Table Using SqlBulkCopy
Let's take an Excel Workbook with a worksheet, called Data, that contains 1000 rows of nonsense data broken into 2 columns, ID and Data.
I want to copy this data into a SQL Server Database Table, called ExcelData, with the same schema.
Just a little bit of code transfers the data from the Excel Spreadsheet into the SQL Server Database Table:
// Connection String to Excel Workbook
string excelConnectionString = @"Provider=Microsoft
.Jet.OLEDB.4.0;Data Source=Book1.xls;Extended
Properties=""Excel 8.0;HDR=YES;""";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select ID,Data FROM [Data$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=.;
Initial Catalog=Test;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelData";
bulkCopy.WriteToServer(dr);
}
}
}
GridView Row Edit, Delete and Update
In this Post I am going to explain a simple light weight GridView Edit, Delete, and Update functionality. We are going to apply this functionality on Northwind Database, Employee table.
Following are the screen shots.Initial Catalog — Your Database name (Northwind in this case).
Integrated Security – True
Integrated Security will access the SQL Server with the current windows identity established on the Operating System. For more information about Integrated Security refer this. We usually place the connection string in the Web.config file under “Configuration ==> ConnectionStrings” section.
Here is my connection string.
<add name=“NorthwindConnectionString“ connectionString=“Data Source=*****(SQL Server Name);Initial Catalog=NorthWind;Integrated Security=True;“/>
</connectionStrings>
To learn more about different type of connection strings refer this.
Then, after we are done with your connection string in the Web.config file let’s move on to the C# code.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(“select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
The First Line using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources. Refer this for Complete Reference.
In the Code you can see I put AutoGenerateColumns=”false”. That means I have to write column names whatever I want to show to the user. If we put AutoGenerateColumns=”True”, that means u don’t have to write any custom code on your page and user can see each and every column in your dataset or datatable whatever you are binding to your gridview.
How can we hide a column in a GridView and access it in the Code behind ?
Writing a Template Field and making it invisible. In the template field I will Place a label or some controls, So that it’s very easy to access those controls in the code behind by using FindControl method.
What is TemplateField, ItemTemplate, and EditItemTemplate?
ItemTemplate is the content to display for the items in the TemplateField.
Take this simple Snippet.
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
In the above Snippet you are seeing a label in Item Template that means whenever we are showing GridView to the user Label will be visible to the user. If he clicks edit (or) in the edit mode he can be able to see the Textbox.
The above piece of code will also do the same as label in ItemTemplate and Textbox in the EditItemTemplate. By default all the boundfields will be trasferred as Textboxes in Edit Mode. To avoid this we need to keep the property ReadOnly as false, Then in the edit mode nothing will happenes. It just visible like a label.
<asp:GridView ID=”GridView1″ runat=”server” GridLines=”None” AutoGenerateColumns=”false” AlternatingRowStyle-BackColor=”#EEEEEE” EditRowStyle-BorderColor=”Red” onrowcancelingedit=”GridView1_RowCancelling” onrowcommand=”GridView1_RowCommand” onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing” onrowupdating=”GridView1_RowUpdating” DataKeyNames=”EmployeeID”>
<Columns>
<asp:TemplateField Visible=”false” HeaderText=”EmployeeID”> <ItemTemplate>
<asp:Label runat=”server” ID=”EmployeeID” Text=’<%#Eval(“EmployeeID”)%>‘ />
</ItemTemplate>
</asp:TemplateField>
<%–<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” />–%>
<ItemTemplate>
<asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Title”>
<asp:Label runat=”server” ID=”Title” Text=’<%#Eval(“Title”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtTitle” Text=’<%#Eval(“Title”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdTitle” ControlToValidate=”txtTitle” ValidationGroup=”var1″ ErrorMessage=”*” /> </EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Country”>
<ItemTemplate>
<asp:Label runat=”server” ID=”Country” Text=’<%#Eval(“Country”) %>‘ />
</ItemTemplate><EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtCountry” Text=’<%#Eval(“Country”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdCountry” ControlToValidate=”txtCountry” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Action”>
<ItemTemplate>
<asp:LinkButton ID=”btnEdit” Text=”Edit” runat=”server” CommandName=”Edit” /> <br />
<asp:LinkButton ID=”btnDelete” Text=”Delete” runat=”server” CommandName=”Delete” />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID=”btnUpdate” Text=”Update” runat=”server” CommandName=”Update” />
<asp:LinkButton ID=”btnCancel” Text=”Cancel” runat=”server” CommandName=”Cancel” />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you see the Last TemplateField part in the above code, I am using the link buttons for edit, update, delete and cancel. May be you may think why am I using link buttons as we are provided with some command field buttons by GridView.
2) Secondly if you want to include a custom field (some button or link) in the same column it’s not possible.
Ok let’s move on to Code behind what we have to do when user clicks Edit, Delete, Update and Cancel
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridData();
}
In the above code snippet as you see GridViewEditEventArgs will give the row number whatever you are editing by NewEditIndex property. So GridView will put the appropriate row into the Edit Mode by assigning row number to its EditIndex property. Then again we have to call that BindGridData () method to bind data for the textboxes.
So once after done with editing data, if we click update the following method will be triggered. It will call OnRowUpdating Event.
1) The First line is to get the Primary Key of the table using DataKeyNames Property of GridView.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label EmployeeID = GridView1.Rows[e.RowIndex].FindControl(“EmployeeID”) as Label; TextBox LastName = GridView1.Rows[e.RowIndex].FindControl(“txtLastName”) as TextBox; TextBox Title = GridView1.Rows[e.RowIndex].FindControl(“txtTitle”) as TextBox;
TextBox Country = GridView1.Rows[e.RowIndex].FindControl(“txtCountry”) as TextBox; String UpdateQuery = string.Format(“UPDATE Employees SET LastName=’{0}’, Title=’{1}’,Country=’{2}’ WHERE EmployeeID = {3}”,LastName.Text, Title.Text,Country.Text, Convert.ToInt32(EmployeeID.Text));
GridView1.EditIndex = -1;
BindGridData(UpdateQuery);
}
private void BindGridData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring)){
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + “;select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
If the user click cancels the following event (OnRowCancelling) will be fired. When you are setting the value of the EditIndex to -1 that means you are exiting from the editmode. So i.e. when user clicks cancel, here we are exiting from the editmode and rebinding the data to the GridView by calling BindGridData method.
protected void GridView1_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridData();
}
If the user clicks the Delete button OnRowDeleting event will be fired. The following is the code for that event. Going into that code we are trying to get the primary key of the employee table(EmployeeID) by using GridView DataKeyNames and then pass the Query to the BindGridData method to bind the updated data to the GridView.
{
string EmployeeID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string Query = “delete Employee where Employee.EmployeeID = “ + EmployeeID;
BindGridData(Query);
}
Happy Coding .
Friday, October 8, 2010
Validation Expressions
| Metacharacter | Match |
|---|---|
| \ | the escape character - used to find an instance of a metacharacter like a period, brackets, etc. |
| . (period) | match any character except newline |
| x | match any instance of x |
| ^x | match any character except x |
| [x] | match any instance of x in the bracketed range - [abxyz] will match any instance of a, b, x, y, or z |
| | (pipe) | an OR operator - [x|y] will match an instance of x or y |
| () | used to group sequences of characters or matches |
| {} | used to define numeric quantifiers |
| {x} | match must occur exactly x times |
| {x,} | match must occur at least x times |
| {x,y} | match must occur at least x times, but no more than y times |
| ? | preceding match is optional or one only, same as {0,1} |
| * | find 0 or more of preceding match, same as {0,} |
| + | find 1 or more of preceding match, same as {1,} |
| ^ | match the beginning of the line |
| $ | match the end of a line |
| POSIX Class | Match |
|---|---|
| [:alnum:] | alphabetic and numeric characters |
| [:alpha:] | alphabetic characters |
| [:blank:] | space and tab |
| [:cntrl:] | control characters |
| [:digit:] | digits |
| [:graph:] | non-blank (not spaces and control characters) |
| [:lower:] | lowercase alphabetic characters |
| [:print:] | any printable characters |
| [:punct:] | punctuation characters |
| [:space:] | all whitespace characters (includes [:blank:], newline, carriage return) |
| [:upper:] | uppercase alphabetic characters |
| [:xdigit:] | digits allowed in a hexadecimal number (i.e. 0-9, a-f, A-F) |
| Character class | Match |
|---|---|
| \d | matches a digit, same as [0-9] |
| \D | matches a non-digit, same as [^0-9] |
| \s | matches a whitespace character (space, tab, newline, etc.) |
| \S | matches a non-whitespace character |
| \w | matches a word character |
| \W | matches a non-word character |
| \b | matches a word-boundary (NOTE: within a class, matches a backspace) |
| \B | matches a non-wordboundary |
- \
The backslash escapes any character and can therefore be used to force characters to be matched as literals instead of being treated as characters with special meaning. For example, '\[' matches '[' and '\\' matches '\'. - .
A dot matches any character. For example, 'go.d' matches 'gold' and 'good'. - { }
{n} ... Match exactly n times
{n,} ... Match at least n times
{n,m} ... Match at least n but not more than m times - [ ]
A string enclosed in square brackets matches any character in that string, but no others. For example, '[xyz]' matches only 'x', 'y', or 'z', a range of characters may be specified by two characters separated by '-'. Note that '[a-z]' matches alphabetic characters, while '[z-a]' never matches. - [-]
A hyphen within the brackets signifies a range of characters. For example, [b-o] matches any character from b through o. - |
A vertical bar matches either expression on either side of the vertical bar. For example, bar|car will match either bar or car. - *
An asterisk after a string matches any number of occurrences of that string, including zero characters. For example, bo* matches: bo, boo and booo but not b. - +
A plus sign after a string matches any number of occurrences of that string, except zero characters. For example, bo+ matches: boo, and booo, but not bo or be. - \d+
matches all numbers with one or more digits - \d*
matches all numbers with zero or more digits - \w+
matches all words with one or more characters containing a-z, A-Z and 0-9. \w+ will find title, border, width etc. Please note that \w matches only numbers and characters (a-z, A-Z, 0-9) lower than ordinal value 128. - [a-zA-Z\xA1-\xFF]+
matches all words with one or more characters containing a-z, A-Z and characters larger than ordinal value 161 (eg. ä or Ü). If you want to find words with numbers, then add 0-9 to the expression: [0-9a-zA-Z\xA1-\xFF]+
Typical examples
- (bo*)
will find "bo", "boo", "bot", but not "b" - (bx+)
will find "bxxxxxxxx", "bxx", but not "bx" or "be" - (\d+)
will find all numbers - (\d+ visitors)
will find "3 visitors" or "243234 visitors" or "2763816 visitors" - (\d+ of \d+ messages)
will find "2 of 1200 messages" or "1 of 10 messages" - (\d+ of \d+ messages)
will filter everything from the last occurrence of "2 of 1200 messages" or "1 of 10 messages" to the end of the page - (MyText.{0,20})
will find "MyText" and the next 20 characters after "MyText" - (\d\d.\d\d.\d\d\d\d)
will find date-strings with format 99.99.9999 or 99-99-9999 (the dot in the regex matches any character) - (\d\d\.\d\d\.\d\d\d\d)
will find date-strings with format 99.99.9999 - (([_a-zA-Z\d\-\.]+@[_a-zA-Z\d\-]+(\.[_a-zA-Z\d\-]+)+))
will find all e-mail addresses
Thursday, October 7, 2010
How to get virtual path from physical path in ASP.NET?
public string GetVirtualPath(string physicalPath)
{
string rootpath = Server.MapPath("~/");
physicalPath = physicalPath.Replace(rootpath, "");
physicalPath = physicalPath.Replace("\\", "/");
return "~/" + physicalPath;
}
Partial Class
In previous versions of Visual Studio classes are confined to a single file. It was not possible to split up a single class into multiple files. In order to split up a class we have to use the keyword “Partial”. The purpose of the Partial Class is to allow more than one programmer to write code for the same class, at the same time.
Example
In the above example, the Employee class is split into 2 parts. The first part defines the GetName() method, and the second part defines the GetAge() method. When you compile this program both parts will be combined and compiled.
The important point to remember is both sections use the keyword Partial and the public access modifier.
Points to considered on creating Partial Class
- All the parts must use the partial keyword.
- During compile time, all the parts should be available to form the final class.
- All the parts should have the same access modifiers. – Public, Private, Protected and etc.,
- Any member declared in the partial class is available to all other parts.
- If any part is abstract, the entire class is abstract
- If any part is sealed, then entire class is sealed.
- If any part has Inheritance, then it applies to the entire class.
- We can create the Partial Structs, Interfaces and methods in the same way as we create partial classes.
- Different parts of the partial calls can inherit from different interfaces.
In the above example two parts are declared as public. In the following example we will create one part as abstract.
If you create an object for the Employee class, you will get the following error: “Cannot create an instance of the abstract class or interface Examples.Employee”. This is because the second part is declared as abstract, so the whole class became abstract. Hence you cannot create an object. We can create nested classes as partial class; even when the main class is not partial.Output
Important Points in Partial Method
Dynamically Add a Control to the Page From a User Control
actualy this can't be done this way, because at this stage the page has loaded all the controls to build and it can't be modiified at this point as per the error message,you can do the following:
1- in the control page_load function place this line
this.Page.LoadComplete+=new EventHandler(addcont); // adds a function to the vent handler to be done after the page completes the loading
2- add this function which is used in the event handler above inside your control :
public void addcont(Object obj, EventArgs e)
{
Label newlable = new Label();
newlable.Text = "TestText here";
newlable.BackColor = System.Drawing.Color.Red;this.Page.Form.Controls.Add(newlable);
}
inside this function write all the controls you want to add to the page, this here adds a lable with a red background, with some test text in it..
I hope this helps,
please do not forget to mark my post as answer if it helps...
have a nice day,
Create Table From Class Files With There Propertys/ Convert GenericList to DataTable
private DataTable GetDataTable(PageEntriesInfo _PageInfo)
{
var dt = new DataTable();
foreach (var Info in typeof(CustomElementInfo).GetProperties())
{
dt.Columns.Add(new DataColumn(Info.Name, Info.PropertyType));
}
foreach (var t in _PageInfo.CustomElements)
{
//CustomElements are SubCategory List
var row = dt.NewRow();
foreach (var Info in typeof(CustomElementInfo).GetProperties())
{
row[Info.Name] = Info.GetValue(t, null);
}
dt.Rows.Add(row);
}
return dt;
}