Pages

Friday, September 28, 2012

Printing in C#

Printing in C#

http://www.c-sharpcorner.com/UploadFile/mgold/PritinginCSharp11222005040630AM/PritinginCSharp.aspx

Print a textbox using c#?


http://answers.yahoo.com/question/index?qid=20081230163003AA4xOaT

 Printing DatagridView


http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/dcb691f5-884d-4a8e-8fa0-b403896d9443/


http://www.vbforums.com/showthread.php?641650-how-to-print-data-from-database-in-C

http://stackoverflow.com/questions/10929037/how-to-save-data-from-datagridview-to-sql-server-2008-r2


http://www.dotnetfunda.com/forums/thread4931-extract-data-from-database-and-print-in-the-cument-.aspx

http://stephenchy520.blog.com/2011/02/28/the-safest-way-to-export-datatable-to-pdf-by-easily-using-c/

http://stackoverflow.com/questions/2054982/how-to-print-in-c-sharp-but-not-through-crystal-report

http://www.dreamincode.net/forums/topic/44330-printing-in-c%23/#/

Thursday, September 27, 2012

how to create ms access BACKUP and RESTORE in c#

http://stackoverflow.com/questions/5337040/create-a-backup-database-with-c-sharp

http://www.c-sharpcorner.com/Forums/Thread/64896/

http://www.daniweb.com/software-development/csharp/threads/202843/take-backup-of-sql-server-database-using-c

http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/4fbdec33-76d3-4e1e-bb33-6427a76665de/

http://vinothnat.blogspot.in/2009/01/how-to-taking-backup-database-using-c.html

http://www.dotnetobject.com/Thread-Mysql-backup-using-c

private void btnBackUp_Click(object sender, EventArgs e)
        {
            string CurrentDatabasePath =Environment.CurrentDirectory + @"\Database3.accdb";
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string PathtobackUp = fbd.SelectedPath.ToString();
               File.Copy(CurrentDatabasePath,PathtobackUp+@"\BackUp.accdb",true);
                MessageBox.Show("Back Up SuccessFull! ");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            string PathToRestoreDB = Environment.CurrentDirectory + @"\Database3.accdb";
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string Filetorestore = ofd.FileName;

                // Rename Current Database to .Bak

                File.Move(PathToRestoreDB, PathToRestoreDB +".bak");

                //Restore the Databse From Backup Folder
                File.Copy(Filetorestore, PathToRestoreDB,true);

            }
        }

Friday, September 21, 2012

Simple Insert, Select, Edit, Update and Delete in Asp.Net GridView control

http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx
 Simple Insert, Select, Edit, Update and Delete in Asp.Net GridView control

Introduction
This article explains the methods of binding Asp.Net GridView control with simple DataSet or DataTable, and also explains the methods like Insert, Edit, Update and Delete function in the GridView control.
You can see most of the articles and tutorials in many websites teach you the way to bind a GridView control to the database with some Data Source controls such as SQLDataSource, ObjectDataSource, AccessDataSource and even XMLDatasource. But this article focus on the other way, by binding the GridView control to the database with the help of simple DataTable and perform adding of new records to the database from the footer row of the GridView control. And on each row, we are going to manipulate the records by editing, updating, cancelling and deleting functions.

Sample Scenario

For demonstration, we are going to fill an ASP.NET GridView control with data from a database. Let us take a simple Customer Table. This customer table contains 6 columns such as Customer Unique Code, Name of the Customer, Gender, City, State and Customer Type. We are going to add new records to the database and populate it in the GridView control. Then record manipulation (edit, update and delete) will be done in each and every column with the server controls such as TextBox and DropDownList. In these 6 columns, we are not going to display Customer Code, and to edit Customer Name and City columns we are going to provide TextBox, to edit Gender and Customer Type we are going to use DropDownList. Additionally, the values for Gender DropDownList will be filled with static values such as Male and Female, other DropDownList for Customer Type, we will be filled dynamically with the values from the Database.

Pre-requisites
Your project or website must be ASP.NET AJAX enabled website. Because we are going to add the GridView in an UpdatePanel. So your GridView control will be look smart without unnecessary postbacks. You need to create a Customer Table with 6 columns for Customer Code[Code], Name[Name], Gender[Gender], City[City], State[State] and Customer Type[Type], with your desired data types. Then create a class file in your App_Code folder and create a Default.aspx along with code-behind file Default.aspx.cs.
Step 1. Create Class File ‘CustomersCls.cs’ 
We need to create a class file to do database manipulations such as select, insert, delete and update data in the Customer Table. So we add a class file as ‘CustomersCls.cs’ in App_Code section. Let us write five methods in the class file as follows
public void Insert(string CustomerName, string Gender, string City, string State, string CustomerType)
{
    // Write your own Insert statement blocks
}

public DataTable Fetch()
{
  // Write your own Fetch statement blocks, this method should return a DataTable
}

public DataTable FetchCustomerType()
{
  // Write your own Fetch statement blocks to fetch Customer Type from its master table and this method should return a DataTable
}

public void Update(int CustomerCode, string CustomerName, string Gender, string City,  string CustomerType)
{
  // Write your own Update statement blocks.
}

public void Delete(int CustomerCode)
{
  // Write your own Delete statement blocks.
}
Step 2: Make Design File ‘Default.aspx’ 

In the Default.aspx page, add an UpdatePanel control. Inside the UpdatePanel, add a GridView, set AutoGenerateColumns as False. Change the ShowFooter Flag to True and set the DataKeyNames your column name for Customer Code and Customer Type, in our case it is Code and Type. Then click on the Smart Navigation Tag of the GridView control, choose Add New Column and add 5 BoundField columns with DataField values as Name, Gender, City, State and Type, plus 2 CommandField columns with one for Edit/Update and another for Delete functions. Now your GridView control is ready. But as first step, we need to add some new records into the database. For that we need to place the controls in the Footer row. So we have to convert all these BoundField columns as TemplateField columns. To do this again, click on the Smart Navigation Tag on the GridView choose Edit Columns, the Field’s property window will open. Select column by column from Name to Customer Type, include also Edit column, and select ‘Convert this field into a TemplateField’. Now all the BoundField columns will be converted to TemplateField columns except the Delete column.

Column[0] – Name

Right click on the GridView control, select Edit Template, choose column[0] – Name, you can view a label placed in the ItemTemplate section and a TextBox placed in the EditItemTemplate section. Add another Texbox in the FooterTemplate section and name it as txtNewName.

Column[1] - Gender

Now again select Edit Template, choose column[1] - Gender, replace the TextBox with a DropDownList, name it as cmbGender, add Male and Female as their ListItem values. On the Edit DataBindings of the cmbGender, add Eval("Gender") to its selectedvalue. Add another DropDownList in the FooterTemplate section and name it as cmbNewGender.

Column[2] –City & Column[3] - State

Add Texboxes in both column’s FooterTemplate section and name it as txtNewCity and txtNewState respectively.
Column[4] - Type

In this column’s EditItemTemplate section, replace the TextBox with a DropDownList, name it as cmbType. Also add another DropDownList in the FooterTemplate section and name it as cmbNewType. Both these DropDownList’s we are going to fill with dynamic data from database. So specify both DropDownList’s DataTextField and DataValueField as Type.

Column[5] - Edit

Just add a link button into the FooterTemplate section, specify its CommandName property as ‘AddNew’.

For your persual, we have provided the complete source code of the GridView control below. The State column in our sample is read-only. So you cannot find TextBox for that column in the EditItemTemplate section.

 view Source Code of the GridView Control<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code, Type"OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" ShowFooter="True" OnRowDeleting="GridView1_RowDeleting"> 
<Columns> 

<asp:TemplateField HeaderText="Name" SortExpression="Name"> <EditItemTemplate> 
  <asp:TextBox ID="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox> 
</EditItemTemplate> 
<FooterTemplate> 
  <asp:TextBox ID="txtNewName" runat="server"></asp:TextBox> </FooterTemplate> 
<ItemTemplate> 
  <asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 

<asp:TemplateField HeaderText="Gender"> 
<EditItemTemplate> 
  <asp:DropDownList ID="cmbGender" runat="server" SelectedValue='<%# Eval("Gender") %>'> 
    <asp:ListItem Value="Male" Text="Male"></asp:ListItem>
    <asp:ListItem Value="Female" Text="Female"></asp:ListItem>
  </asp:DropDownList> 
</EditItemTemplate> 
<ItemTemplate> 
  <asp:Label ID="Label2" runat="server" Text='<%# Eval("Gender") %>'></asp:Label> 
</ItemTemplate> 
<FooterTemplate> 
  <asp:DropDownList ID="cmbNewGender" runat="server" >
    <asp:ListItem Selected="True" Text="Male" Value="Male"></asp:ListItem> 
    <asp:ListItem Text="Female" Value="Female"></asp:ListItem> </asp:DropDownList> 
</FooterTemplate> 
</asp:TemplateField> 

<asp:TemplateField HeaderText="City"> 
<EditItemTemplate> 
  <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox> 
</EditItemTemplate> 
<FooterTemplate> 
  <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox> 
</FooterTemplate> 
<ItemTemplate> 
  <asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 

<asp:TemplateField HeaderText="State" SortExpression="State"> 
<EditItemTemplate> 
  <asp:Label ID="Label1" runat="server" Text='<%# Eval("State") %>'></asp:Label> 
</EditItemTemplate> 
<FooterTemplate> 
  <asp:TextBox ID="txtNewState" runat="server" ></asp:TextBox> 
</FooterTemplate> 
<ItemTemplate> 
  <asp:Label ID="Label4" runat="server" Text='<%# Bind("State") %>'></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 

<asp:TemplateField HeaderText="Type"> 
<EditItemTemplate> 
  <asp:DropDownList ID="cmbType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList> 
</EditItemTemplate> 
<ItemTemplate> 
  <asp:Label ID="Label5" runat="server" Text='<%# Eval("Type") %>'></asp:Label> 
</ItemTemplate> 
<FooterTemplate> 
  <asp:DropDownList ID="cmbNewType" runat="server" DataTextField="Type" DataValueField="Type"> </asp:DropDownList> 
</FooterTemplate> 
</asp:TemplateField> 

<asp:TemplateField HeaderText="Edit" ShowHeader="False"> 
<EditItemTemplate> 
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton> 
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton> 
</EditItemTemplate> 
<FooterTemplate> 
  <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton> 
</FooterTemplate> 
<ItemTemplate> 
  <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" /> 

</Columns> 
</asp:GridView>
Step 3: Make Code-behind File ‘Default.aspx.cs’ 

Now we are going to do the code-behind part of this page. Les us explain you event by event coding on each methods. In the code-behind page, create an instance for the Customer class as follows

CustomersCls customer=new CustomersCls();

Then create a private method 'FillCustomerInGrid' to retrieve the existing customer list from the database and bind it to the GridView. The CustomersCls class’s Fetch() method is used and it returns the data to a DataTable. On first stage it will return empty rows. So you cannot see any header, data or even footer rows of the GridView control. You can only see an empty space or you see only the EmptyDataText. So you cannot add any new data from the footer row.

private void FillCustomerInGrid()
{
   DataTable dtCustomer= customer.Fetch();

 if (dtCustomer.Rows.Count>0)
 {
    GridView1.DataSource = dtCustomer;
    GridView1.DataBind();
 }
 else
 {
      dtCustomer.Rows.Add(dtCustomer.NewRow());
      GridView1.DataSource = dtCustomer;
      GridView1.DataBind();

      int TotalColumns = GridView1.Rows[0].Cells.Count;
      GridView1.Rows[0].Cells.Clear();
      GridView1.Rows[0].Cells.Add(new TableCell());
      GridView1.Rows[0].Cells[0].ColumnSpan = TotalColumns;
      GridView1.Rows[0].Cells[0].Text = "No Record Found";
  }
}

In this article, we have provided a workaround to fix this problem. Closely look at the method FillCustomerInGrid, there is a conditional statement to check the rows exists in DataTable or not. Now go to the else part of the if statement, see the block of code we provided there. Simply we have added an empty row to the DataTable. Then bind it to the GridView control. To give a professional look to the GridView control, we do little bit more by providing ColumnSpan and set a Text as "No Record Found", this text will be displayed if the GridView is empty without any rows and you can see both the Header and Footer of the GridView control.

Initialize GridView control

In the page load event, we have to call this FillCustomerInGrid method as follows,

protected void Page_Load(object sender, EventArgs e)
{
  If (!IsPostBack)
  {
     FillCustomerInGrid();
   }
}

Fill DropDownList in GridView with dynamic values

In column[4] - Type, there are two DropDownList controls, one in the EditItemTemplate section (cmbType) and another in FooterTemplate (cmbNewType). We have to fill both these DropDownList controls with some dynamic data. If you look at our CustomersCls class, we have a separate method called FetchCustomerType. In the RowDataBound event of the GridView control insert the following code.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");

  if (cmbType != null)
  {
    cmbType.DataSource = customer.FetchCustomerType();
    cmbType.DataBind();
    cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();
   }
 }

if (e.Row.RowType == DataControlRowType.Footer)
{
    DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
    cmbNewType.DataSource = customer.FetchCustomerType();
    cmbNewType.DataBind();
 }

}


Previously in this article, we have set the DataKeyNames values as Code, Type. If you see in the above code, we use one of the DataKeyNames value as the SelectedValue for the cmbType control, this is to retain the value of the cmbType in EditMode. The index value of Code is 0 and Type is 1. So we use as follows

cmbType.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Values[1].ToString();

So far we have initialized the GridView control with the datatable and also make some values to be filled in the Footer DropDownList cmbNewType. Run the application, you can see the GridView only with the Footer row and data in the cmbNewType control. Let us start to code for adding new records into the database when we click ‘Add New’ linkbutton.

Add New Records from GridView control

Create an event for the GridView’s RowCommand and add the following code in it.

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName.Equals("AddNew"))
  {
   TextBox txtNewName=(TextBox)GridView1.FooterRow.FindControl("txtNewName");
   DropDownList cmbNewGender = (DropDownList)GridView1.FooterRow.FindControl("cmbNewGender");
   TextBox txtNewCity = (TextBox)GridView1.FooterRow.FindControl("txtNewCity");
   TextBox txtNewState = (TextBox)GridView1.FooterRow.FindControl("txtNewState");
   DropDownList cmbNewType = (DropDownList)GridView1.FooterRow.FindControl("cmbNewType");

   customer.Insert(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue) ;
      FillCustomerInGrid();
  }
}

In the above code, we are declaring and finding the controls in the GridView’s footer section and use the CustomersCls class insert method to add the new data into the database. Then we are calling the FillCustomerInGrid method to fill the GridView control with the newly inserted values. Now save everything and run your application. Put some test data in the Textboxes and select some values in the DropDownLists and click on the Add New linkbutton. You can see data inserted into the database and listed in the GridView control.

Edit and Update in GridView

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

  GridView1.EditIndex = e.NewEditIndex; 
  FillCustomerInGrid(); 
}

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) 

  GridView1.EditIndex = -1;
   FillCustomerInGrid(); 
}

You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event. 

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
  DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
  TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
  DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");

 customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text, cmbGender.SelectedValue,txtCity.Text, cmbType.SelectedValue);
  GridView1.EditIndex = -1;
  FillCustomerInGrid();
}

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Delete in GridView 

To delete a row from the customer table, add the following lines of code in the GridView’s RowDeleting event. Here you have to pass the unique Code of customer which is in GridView1.DataKeys[e.RowIndex].Values[0].ToString() to the Delete method of the CustomersCls class. 

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  customer.Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString());
  FillCustomerInGrid();
}


This article gives you some basic idea of inserting data into database from a GridView control and does all database manipulations within the GridView without binding it with any Asp.Net Data source controls.

Output:
 Sample For Simple Insert, Select, Edit, Update and Delete in GridView
This the sample page for making simple insert, select, edit, update and delete functions in GridView control. You can entered your own data in the controls and click Add New link to add into the GridView control. Then you can do Edit, Update and Delete functions. Even you can try by deleting all the existing records and insert new records from the controls placed in the footer section of the GridView control.
Customer List
NameGenderCityStateTypeEditDelete
AlexMaleOxfordAlabamaRetailerEditDelete
ChristianaFemaleChesterNew YorkRetailerEditDelete
JenifferFemaleDestinFloridaWholesaleEditDelete
LeverlockMaleBaytownTexasWholesaleEditDelete
MarkMaleAvon ParkFloridaRetailerEditDelete
ChaitnayaMaleVijayawadaAndhra PradeshWholesaleEditDelete
Add New 

Monday, September 17, 2012

MS Access Date and Time with ASP.NET

http://www.codingforums.com/showthread.php?t=150409

http://www.mikesdotnetting.com/Article/92/MS-Access-Date-and-Time-with-ASP.NET

MS Access Date and Time with ASP.NET

Getting odd results and unexpected errors when working with Dates and Times in Access through ASP.NET is a common problem. Here's an overview of the Access DateTime data type, and some resolutions to the more frequently encountered errors.

First, it's worth pointing out that the ONLY data type within Access that is appropriate for storing dates and times is the DATETIME data type. It is not uncommon to find that people are trying to work with dates and times stored in TEXT fields. The problem with this approach is that any sorting on dates in TEXT fields will only be done alphabetically because they will be treated as strings.
The Access DATETIME is actually an OLE Automation Date datatype. It is implemented as a double-precision (64bits) floating-point number. The time and date at the moment I start to type this is 08:34:27 on December 13th, 2008. As an OLE Automation Date, this appears as 39795.3572615509. The integer portion to the left hand side of the decimal point represents the number of days since December 31st 1899, while the the proportion of the current day in seconds that has elapsed since midnight appears after the point. 8.00am is one third of the day, or 0.33 of a day. At midday exactly, the OLE Automation Date will be 39795.5. You will also see this behaviour with Excel. For example, if you type 13/12/2008 into a cell, then select the cell directly below and press Ctrl + ' (the combination that copies the contents of the cell directly above) you will get 39795, unless the new cell has been formatted to a specific Date and Time format.
Inserting the current Date into Access can be done in a number of ways. The first example shows how to do this using the .Net DateTime data type directly:
  
string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|mbbase.mdb";
using (OleDbConnection cn = new OleDbConnection(connect))
{
    string sql = "INSERT INTO TEST (MyDateTime) VALUES (?)";
    OleDbCommand cmd = new OleDbCommand(sql, cn);
   cmd.Parameters.AddWithValue(""DateTime.Now.Date);
   cn.Open();
   cmd.ExecuteNonQuery();
}
  
This results in 13/12/2008 appearing in my copy of Access with the setting set on my machine as UK dd/mm/yyyy.
Probably the easiest way, however, with the current date is to use the built-in Date() function within Access and forget all about a parameter. The Date() function gets the current system date:
  
string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|mbbase.mdb";
using (OleDbConnection cn = new OleDbConnection(connect))
{
    string sql = "INSERT INTO TEST (MyDateTime) VALUES (Date())";
    OleDbCommand cmd = new OleDbCommand(sql, cn);
   cn.Open();
   cmd.ExecuteNonQuery();
}
  
The Jet Provider is pretty good at parsing strings into Ole Automation Dates, so long as the string follows the format of a recognisable Date. I'll add a TextBox and a Button to a form, and use that as the source of the value that will be entered:
  
<form id="form1" runat="server">
<div>
    <asp:TextBox ID="TextBox1" runat="server" />
    <br />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>
</form>
  
Next, I'll change the code-behind to put the processing in the button click event:

protected void Button1_Click(object sender, EventArgs e)
{
  string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|mbbase.mdb";
  using (OleDbConnection cn = new OleDbConnection(connect))
  {
    string sql = "INSERT INTO TEST (MyDateTime) VALUES (?)";
    OleDbCommand cmd = new OleDbCommand(sql, cn);
    cmd.Parameters.AddWithValue("", TextBox1.Text);
    cn.Open();
    cmd.ExecuteNonQuery();
  }
}

Using this set up, all of the following strings can be entered into the TextBox and inserted into the database DATETIME field without problem:
13 Dec 2008
13 December 2008
13 Dec 08
13 December 08
Dec 13 08
Dec 13 2008
13/12/2008
13/12/08
13-12-08
13 12 08
13 12 2008
Along with some others, but that should do for the time being.
The question is how do you get your users to enter the date in an acceptable format? There are a number of UI ways in which this can be done. You can tell them, by adding instructions to the form, or you can simply use a Calendar control (Calendar Extender from the Ajax Control Toolkit is good, as are many of the jQuery date picker plug ins) and set the format yourself. Or you can provide dropdown lists for day, month and year, and control the format that way.
The Time part of a DateTime is a tiny bit different. For example trying to pass in DateTime.Now will result in a "Data type mismatch in criteria expression" error. The reason for this is that the .Net DateTime.Now property includes milliseconds which can be seen by writing the current time using the following format:

String.Format("{0:yyyy-MM-dd hh:mm:ssss:ffffff}"DateTime.Now)

Access has no way of handling milliseconds, because if we remember, the right hand side of the OLE Automation Date only holds the proportion of the elapsed day in whole seconds. For the current time, the simplest solution is to use the Access built-in function Now() in your SQL, just as we did with Date() earlier. If you wanted to add another time, there are various options. The ToString() method removes the milliseconds from a .Net DateTime object, so this is one way to approach it:

protected void Button1_Click(object sender, EventArgs e)
{
  string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|mbbase.mdb";
  using (OleDbConnection cn = new OleDbConnection(connect))
  {
    string sql = "INSERT INTO TEST (MyDateTime) VALUES (?)";
    OleDbCommand cmd = new OleDbCommand(sql, cn);
    cmd.Parameters.AddWithValue(""DateTime.Now.AddDays(-10).ToString());
    cn.Open();
    cmd.ExecuteNonQuery();
  }
}

Another is to use the ToOADate() method, which converts the .Net DateTime to an Ole Automation Date, which as we have established is what Access really likes:

protected void Button1_Click(object sender, EventArgs e)
{
  string connect = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=|DataDirectory|mbbase.mdb";
  using (OleDbConnection cn = new OleDbConnection(connect))
  {
    string sql = "INSERT INTO TEST (MyDateTime) VALUES (?)";
    OleDbCommand cmd = new OleDbCommand(sql, cn);
    cmd.Parameters.AddWithValue(""DateTime.Now.AddHours(36).ToOADate());
    cn.Open();
    cmd.ExecuteNonQuery();
  }
}

Again, there are a fair number of valid formats for times entered as strings into the TextBox:
13/12/2008 20:00:00
December 13 2008 8:00:00 PM
13 Dec 08 08:00:00
2008-12-13 18:00:00
etc.

Regional Settings

Generally, you will have the Access database on the same machine as the web application is running on, so there is unlikely to be any variation in terms of date formats. However, it is worth pointing out that the built-in Access functions, Date() and Now() pick up the current system time from the machine on which the database resides. Consequently, it come be a problem developing an application on a machine with UK Regional settings, where the date format is generally dd/mm/yyyy, and then transferring this to a US-based server, where the regional settings will expect mm/dd/yyyy. Changing the format in the Table Designer within Access has absolutely no effect on the underlying values. As we have already established, the underlying values are stored as double-precision floating-point numbers, not as formatted dates and times. The formatting option only allows you to instruct Access as to how you would like to see dates and times in Table view, or in Forms and Reports.
If you think there is any chance that your application may run on a machine where you have no control over the Regional Settings, or they are unknown, you are always best advised to input dates in the format yyyy-mm-dd, or ToOADate(). This way, there is no likelihood of the 3rd of July becoming the 7th of March at some stage in the future. Certainly when querying dates within Access, it is always best to use the yyyy-mm-dd format. In addition, using parameters eliminates most problems encountered when using delimiters with dates and times.

Parameter Queries in ASP.NET with MS Access

http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access


Parameter Queries in ASP.NET with MS Access

A selection of code samples for executing queries against MS Access using parameters.

Making use of the ASP.NET 2.0 datasource controls is fine, but it is important to understand how to manually create data access code. Best practice dictates that, at the very least, parameters are used to represent values that are passed into the SQL to be executed, rather than un-sanitised values straight from the user. The main reason for this cannot be over-emphasised in terms of its importance - it protects the application against SQL Injection attacks. In addition, parameters do not require delimiters. Therefore there is no need to worry about octothorpes (#) or apostrophes for dates, or doubling single quotes in strings.
These samples all assume that the values being passed into the parameters have been properly validated for datatype, existence, range etc, according to the business rules for the application. The serverside validation code is not included, as it will differ from app to app, and is not the focus of these samples anyway. However, it is important to stress that all user input must be validated server-side before being included in a SQL statement. Better to reject it outright, rather than have to unpick rubbish that pollutes the database...
The required components are an OleDbConnection object, a ConnectionString property, an OleDbCommand object and an OleDbParameterCollection. These all reside in the System.Data.OleDb namespace, which needs to be referenced. Also, the connection string is held in the Web.Config, and a static method GetConnString() has been created in a class called Utils (also static) to retrieve it:
[C#]
public static string GetConnString()
{
  return WebConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
}
[VB]
Public Shared Function GetConnString() As String
  Return WebConfigurationManager.ConnectionStrings("myConnStr").ConnectionString
End Function

For simplicity, you can replace Utils.GetConnString with a valid Access connection string such as:

"Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|Northwind.mdb"
To make use of |DataDirectory| make sure that your database file is in the App_Data folder of your web site.
OleDb Parameters are recognised by their position, not by their name. Consequently, it is vital to ensure that parameters are added to the collection in the order they appear in the SQL, otherwise a "Too few parameters..." exception could occur. At the very least, your values will get inserted into the wrong fields, or nothing happens at all. For the sake of code readability, AddWithValues(stringobject) can take a non-empty string giving a name to the parameter, although an empty string ("") will do.
One final note about parameter markers: in the samples below, the markers are represented by question marks ( ? ). Access (or the Jet provider) is also happy to work with SQL Server-style parameter markers that are prefixed with @, so the first example CommandText can be replaced with:

"Insert Into Contacts (FirstName, LastName) Values (@FirstName, @LastName)"

INSERT

[C#]
string ConnString = Utils.GetConnString();
string SqlString = "Insert Into Contacts (FirstName, LastName) Values (?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

[VB]
Dim ConnString As String = Utils.GetConnString()
Dim SqlString As String = "Insert Into Contacts (FirstName, LastName) Values (?,?)"
Using conn As New OleDbConnection(ConnString)
  Using cmd As New OleDbCommand(SqlString, conn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
    conn.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

UPDATE

[C#]
string ConnString = Utils.GetConnString();
string SqlString = "Update Contacts Set FirstName = ?, LastName = ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

[VB]
Dim ConnString As String = Utils.GetConnString()
Dim SqlString As String = "Update Contacts Set FirstName = ?, LastName = ?"
Using conn As New OleDbConnection(ConnString)
  Using cmd As New OleDbCommand(SqlString, conn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
    conn.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

DELETE

[C#]
string ConnString = Utils.GetConnString();
string SqlString = "Delete * From Contacts Where FirstName = ? And LastName = ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

[VB]
Dim ConnString As String = Utils.GetConnString()
Dim SqlString As String = "Delete * From Contacts Where FirstName = ? And LastName = ?"
Using conn As New OleDbConnection(ConnString)
  Using cmd As New OleDbCommand(SqlString, conn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
    conn.Open()
    cmd.ExecuteNonQuery()
  End Using
End Using

SELECT

[C#]
string ConnString = Utils.GetConnString();
string SqlString = "Select * From Contacts Where FirstName = ? And LastName = ?";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.Text;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);

    conn.Open();
    using (OleDbDataReader reader = cmd.ExecuteReader())
    {
      while (reader.Read())
      {
        Response.Write(reader["FirstName"].ToString() + " " + reader["LastName"].ToString());
      }
    }
  }
}

[VB]
Dim ConnString As String = Utils.GetConnString()
Dim SqlString As String = "Select * From Contacts Where FirstName = ? And LastName = ?"
Using conn As New OleDbConnection(ConnString)
  Using cmd As New OleDbCommand(SqlString, conn)
    cmd.CommandType = CommandType.Text
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
    conn.Open()
    Using reader As OleDbDataReader = cmd.ExecuteReader()
      While reader.Read()
        Response.Write(reader("FirstName").ToString() + " " + reader("LastName").ToString())
      End While
    End Using
  End Using
End Using

Saved Queries

The code samples above will work equally well with minimal changes for Saved Queries in MS Access. The CommandType will need to be changed to "StoredProcedure", and the name of the query needs to be passed as a string in place of the SQL statement. As an example, if a Saved Query was created in Access called AddContact, this is how the INSERT example would alter:
[C#]
string ConnString = Utils.GetConnString();
string SqlString = "AddContact";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
  using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
  {
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text);
    cmd.Parameters.AddWithValue("LastName", txtLastName.Text);
    conn.Open();
    cmd.ExecuteNonQuery();
  }
}

[VB]
Dim ConnString As String = Utils.GetConnString()
Dim SqlString As String = "AddContact"
Using Conn As New OleDbConnection(ConnString)
  Using Cmd As New OleDbCommand(SqlString, Conn)
    Cmd.CommandType = CommandType.StoredProcedure
    Cmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
    Cmd.Parameters.AddWithValue("LastName", txtLastName.Text)
    Conn.Open()
    Cmd.ExecuteNonQuery()
  End Using
End Using
You may end up using a legacy Access database, which has embedded spaces in the names of the queries. I know - only an idiot does this sort of thing. Well, the download version of Northwind.mdb (from Microsoft) has embedded spaces in object names... Anyway, the way to get round this is to surround the query name with [ ] brackets:

string query = "[Current Product List]";