Saturday, 16 July 2011

Merge Statement – One Statement for INSERT, UPDATE, DELETE

MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it.
One of the most important advantage of MERGE statement is all the data is read and processed only once. In previous versions three different statement has to be written to process three different activity (INSERT, UPDATE or DELETE), however using MERGE statement all update activity can be done in one pass of database table. This is quite an improvement in performance of database query.
In our example we will consider three main conditions while we merge this two tables.
1.    Delete the records whose marks are more than 250.
2.    Update marks and add 25 to each as internals if records exist.
3.    Insert the records if record does not exists.
Now we will write MERGE process for tables created earlier. We will make sure that we will have our three conditions discussed above are satisfied.
MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);

There are two very important points to remember while using MERGE statement.
·         Semicolon is mandatory after the merge statement.
·         When there is a MATCH clause used along with some condition, it has to be specified first amongst all other WHEN MATCH clause.

Monday, 4 July 2011

GridView


Gridview:

*Suppose we have a text box in the gridview and our requirement is to send the value of the  value of the row     which have checked. We have to send the textbox value which user have  entered in runtime by user, along with one column value. Then we will write the code like  below.

    foreach (GridViewRow row in gdvShowList.Rows)
    {
          CheckBox chk;
          chk = ((CheckBox)row.FindControl("chkSelect"));
          if (chk.Checked)
          {
               txt = ((TextBox)row.FindControl("txtRemark"));
               sb.Append(row.Cells[1].Text + "~" + (txt.Text) + "`");
           }
    }
 In the backend we have to split the string and store the those columns value in the  respective column.

* The RowStyle-CssClass property of the GridView has been set as “rowHover”; when GridView renders on the page, each row of the GridView (GridView is rendered on the page as html table) is rendered with “rowHover” CSS class that only takes effect when we mouse hover on the GridView row.

Steps to follow
Define following CSS style in the .css file or on the .aspx page itself.

ASPX Page:

<style type="text/css">
#GridView1 tr.rowHover:hover
{
background-color: Yellow;
font-family: Arial;
}
</style>
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" RowStyle-CssClass="rowHover" ClientIDMode="Static" />
Note that the important thing here is the ID of the GridView. When GridView rendered on the page it’s id should be GridView1 that is why we have set ClientIDMode=static.

The CSS class name is rowHover with filtration that instruct the browser that this CSS class should be applied only to the element having id as “GridView1” with “tr” element having class=”rowHover” and only when user mouse over it.

In this CSS class we have specified the background color to “Yellow” and font family to “Arial”.

If you are working on a master page then you can do the above in the following ways .

Write the below code in Row_Created event of gridview.

public void ItemDataBoundEventHandler1(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    e.Row.Attributes.Add("onmouseover","this.style.backgroundColor='Silver'");
    e.Row.Attributes.Add("onmouseout","this.style.backgroundColor='#FFFBD6'");
  }
}

or You can write the below code in Row_created event of gridview


if (e.Row.RowType == DataControlRowType.Header)
   e.Row.CssClass = "header";

//Add CSS class on normal row.
if (e.Row.RowType == DataControlRowType.DataRow &&
          e.Row.RowState == DataControlRowState.Normal)
   e.Row.CssClass = "normal";

//Add CSS class on alternate row.
if (e.Row.RowType == DataControlRowType.DataRow &&
          e.Row.RowState == DataControlRowState.Alternate)
   e.Row.CssClass = "alternate";

You have to write the CSS code for header,normal and alternate.


*Change ASP.NET GridView Header Text at Runtime

write the following code in the RowDataBound event to change the HeaderText of the 3rd column. Note that column index starts from zero.

protected void GridVie1_RowDataBound(object sender, GridViewRowEventArgs e)
{
// check for a condition
if (1 == 1)
{
GridView1.Columns[2].HeaderText = "Price(10 Units)";
}
}

*Display Page count in ASP.NET GridView
protected void GridView1_RowDataBound(object sender,
                                            GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = (GridView1.PageIndex + 1) + " of " + GridView1.PageCount;
    }
}

*Set Width of GridView TextBox in Edit mode
To modify the width of a TextBox (inside the GridView control) when the GridView is in Edit Mode, use any of the two approaches:

Using ControlStyle

<asp:GridView ID="gvCustom" runat="server">
    <Columns>
        <asp:BoundField DataField="EmpID" HeaderText="EmployeeID" >
            <ControlStyle Width="150" />
        </asp:BoundField>
    </Columns>
</asp:GridView>
Use ControlStyle CSS Class (Recommended)

<style type="text/css">
.cssWdth
{
    width: 150px;
}
</style>
and in the GridView

<asp:GridView ID="gvCustom" runat="server">
    <Columns>
        <asp:BoundField DataField="EmpID" HeaderText="EmployeeID"
        ControlStyle-CssClass="cssWdth" />
    </Columns>
</asp:GridView>
**************************************************************
If you want to hide the column at run time then do the following :


protected void gdvAdminReport_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[2].Visible = false;
            e.Row.Cells[3].Visible = false;
        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Visible = false;
            e.Row.Cells[2].Visible = false;
            e.Row.Cells[3].Visible = false;
        }
    }


The RowDataBound event is raised when a data row (represented by a GridViewRow object) is bound to data in the GridView control.This enables you to provide an event-handling method that performs a custom routine, such as modifying the values of the data bound to the row, whenever this event occurs.

decimal priceTotal = 0;
int quantityTotal = 0;
void detailsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // add the UnitPrice and QuantityTotal to the running total variables
        priceTotal += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, _
          "UnitPrice"));
        quantityTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
          "Quantity"));
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = "Totals:";
        // for the Footer, display the running totals
        e.Row.Cells[1].Text = priceTotal.ToString("c");
        e.Row.Cells[2].Text = quantityTotal.ToString("d");
     
        e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
        e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
        e.Row.Font.Bold = true;
    }
}

***********************************************************************************
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
        if(e.Row.RowType == DataControlRowType.DataRow)
        {
            Decimal ProductPrice = (decimal)DataBinder.Eval(e.Row.DataItem, "UnitPrice");
            if(ProductPrice<20)
            {
                e.Row.ForeColor = System.Drawing.Color.Crimson;
                e.Row.Font.Italic = true;
                e.Row.BackColor = System.Drawing.Color.LightPink;
            }
        }

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

if(e.Row.RowType == DataControlRowType.DataRow)
    {
      // Display the company name in italics.
      e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";

    }
******************************************************************************************
Merge GridView Header Columns

<asp:GridView ID="gvCustom" runat="server" AutoGenerateColumns="false"
        AllowPaging="true" PageSize="5" OnPageIndexChanging="gvPaging"
        OnRowCreated="gvCustom_RowCreated">

Finally write the following code in the RowCreated event


protected void gvCustom_RowCreated(object sender,
    GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        GridView header = (GridView)sender;
        GridViewRow gvr = new GridViewRow(0, 0,DataControlRowType.Header,DataControlRowState.Insert);
        TableCell tCell = new TableCell();
        tCell.Text = "DevCurry Employee Information";
        tCell.ColumnSpan = 4;
        tCell.HorizontalAlign = HorizontalAlign.Center;
        gvr.Cells.Add(tCell);
        // Add the Merged TableCell to the GridView Header
        Table tbl = gvCustom.Controls[0] as Table;
        if (tbl != null)
        {
            tbl.Rows.AddAt(0, gvr);
        }
    }
}
***********************************************************************************************
Add an Image Command Field to a GridView at runtime

If you were looking out to programmatically add an Image Command Field to a GridView, here’s how to do so:

C#

if (!Page.IsPostBack)
{
    CommandField field = new CommandField();
    field.ButtonType = ButtonType.Image;
    field.SelectImageUrl = "~/Images/MyPic.GIF";
    field.ShowSelectButton = true;
    field.HeaderText = "Select";
    GridView1.Columns.Add(field);
    GridView1.DataBind();
}
***************************************************************************************************
Set the Line Color Between Rows in an ASP.NET GridView


Have you wondered how to set the color between two rows in an ASP.NET GridView. The GridView control does not provide a direct attribute for setting a color to the lines between two rows. But here’s how to do it using CSS:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Change Color of Lines</title>
    <style type="text/css">
        .gridLines td
        {
            border-bottom: 1px solid Gray;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
        GridLines="Horizontal" CssClass="gridLines" DataKeyNames="ID" >
        <Columns>
            ...
        </Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>
********************************************************************************************************
Programmatically Load a GridView Row in Edit Mode


A user in asp.net forums asked a question about loading a GridView Row programmatically in EditMode. It’s quite simple actually. You just have to set the EditIndex to the row number that needs to be edited and bind the GridView with the datasource. Here’s an example:

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Employee emp = new Employee();
        listEmp = emp.GetEmployees();
        // Add Row in Edit Mode
        GridView1.EditIndex = 3;
        // Bind GridView to its Source
        this.GridView1.DataSource = listEmp;
        this.GridView1.DataBind();
    }
}
*******************************************************************************************
Display Page count in ASP.NET GridView


Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to display the page count in an ASP.NET GridView control

In one of our previous articles, we saw how to Highlight the current page in an ASP.NET GridView pager. Let us extend the example, to show the page count too.

The first step is to set the ShowFooter property to true and add a RowDataBound event to the GridView, as shown below



Next write the following code in the GridView_RowDataBound event

protected void GridView1_RowDataBound(object sender,
                                            GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Footer)
    {
        e.Row.Cells[0].Text = (GridView1.PageIndex + 1) + " of " + GridView1.PageCount;
    }
}
**************************************************************************************************
Add a Row Number to the GridView


Here’s a simple way to add a Row Number to the GridView. Just add the following tags to your <columns> section of your GridView

 <Columns>                    
     <asp:TemplateField HeaderText="RowNumber">
         <ItemTemplate>
                 <%# Container.DataItemIndex + 1 %>
         </ItemTemplate>
     </asp:TemplateField>
     ...
</Columns>
******************************************************************************************************
How to read hidden field data in GridView Asp.net C#

         <Columns>
             <asp:CommandField ShowSelectButton="True" />

             <asp:TemplateField HeaderText="Product Name">

             <ItemTemplate>

             <asp:HiddenField runat="server" ID="HiddenField1" Value='<%#Eval("ID")%>'></asp:HiddenField>

             <asp:Label runat="server" ID="Label2" Text ='<%#Eval("Name")%>'></asp:Label>

             </ItemTemplate>

             </asp:TemplateField>

             <asp:BoundField DataField="Description" HeaderText="Description" />

             <asp:BoundField DataField="Color" HeaderText="Color" />

             <asp:BoundField DataField="Size" HeaderText="Size" />

         </Columns>

Now under SelectedIndexChanged event write the below code to read hidden field value within gridview template column:        

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

    {
        string sValue = ((HiddenField)GridView1.SelectedRow.Cells[1].FindControl("HiddenField1")).Value;

        Response.Write("Product Id=" + sValue);
    }
   
****************************************************************************
Merge merging or Split spliting GridView Header Row or columns in Asp.Net 2.0 / 3.5

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            GridView HeaderGrid = (GridView)sender;

            GridViewRow HeaderRow = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);

            TableCell Cell_Header = new TableCell();

            Cell_Header.Text = "Hierarchy";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 2;

            HeaderRow.Cells.Add(Cell_Header);



            Cell_Header = new TableCell();

            Cell_Header.Text = "Product Name";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 1;

            Cell_Header.RowSpan = 2;

            HeaderRow.Cells.Add(Cell_Header);


            Cell_Header = new TableCell();

            Cell_Header.Text = "Quantity";

            Cell_Header.HorizontalAlign = HorizontalAlign.Center;

            Cell_Header.ColumnSpan = 3;

            HeaderRow.Cells.Add(Cell_Header);


            GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

        }

    }
******************************************************************************************
GridView.RowDeleted Event

The RowDeleted event is raised when a row's Delete button is clicked, but after the GridView control deletes the row. This enables you to provide an event-handling method that performs a custom routine, such as checking the results of the delete operation, whenever this event occurs.

The following example demonstrates how to use the RowDeleted event to check the result of the delete operation. A message is displayed to indicate to the user whether the operation succeeded.

void CustomersGridView_RowDeleted(Object sender, GridViewDeletedEventArgs e)
  {

    // Display whether the delete operation succeeded.
    if(e.Exception == null)
    {
      Message.Text = "Row deleted successfully.";
    }
    else
    {
      Message.Text = "An error occurred while attempting to delete the row.";
      e.ExceptionHandled = true;
    }

  }
*********************************************************************************************
GridView.RowUpdated Event

The RowUpdated event is raised when a row's Update button is clicked, but after the GridView control updates the row. This enables you to provide an event-handling method that performs a custom routine, such as checking the results of the update operation, whenever this event occurs.

The following example demonstrates how to use the RowUpdated event to check the result of the update operation. A message is displayed to indicate to the user whether the operation succeeded.

 void CustomersGridView_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
  {

    // Indicate whether the update operation succeeded.
    if(e.Exception == null)
    {
      Message.Text = "Row updated successfully.";
    }
    else
    {
      e.ExceptionHandled = true;
      Message.Text = "An error occurred while attempting to update the row.";
    }
  }

********************************************
If you want that in the updating mode you want to bind the dropdownlist & select the required value then you can do in the following ways .

<asp:TemplateField HeaderText="Gender">
 <ItemTemplate>
 <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Sex") %>'>
 </asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
 <asp:RadioButtonList ID="rbGenderEdit" runat="server">
 <asp:ListItem>Male</asp:ListItem>
 <asp:ListItem>Female</asp:ListItem>
 </asp:RadioButtonList>
 </EditItemTemplate>
 </asp:TemplateField>

In the row databound event you have to write the below code

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 DataRowView dRowView = (DataRowView)e.Row.DataItem;
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
 if ((e.Row.RowState & DataControlRowState.Edit) > 0)
 {
 RadioButtonList rblGender = (RadioButtonList)e.Row.FindControl("rbGenderEdit");
 DropDownList ddlStatus = (DropDownList)e.Row.FindControl("ddlStatusEdit");
 rblGender.SelectedValue = dRowView[2].ToString();
 dlStatus.SelectedValue = dRowView[3].ToString();
}
}       
}
*****************************************************
If from the databse NULL value is returning but you want to the different text in place of NULL then you can achieve by calling the server side method in the following ways.
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# CheckNull(Eval("Location")) %>'/>
</ItemTemplate> </asp:TemplateField>
In the server side code :

protected string CheckNull(object objGrid)
{
  if (object.ReferenceEquals(objGrid, DBNull.Value))
  {
     return "No Record Found";
  }
  else
  {
      return objGrid.ToString();
  }
}
***************************************************************
Suppose in your Gridview there is a Linkbutton. You want to redirect to a different page by clicking on that button. You also want to send some value using querystring then do the following.
<asp:TemplateField HeaderText="Name">
 <ItemTemplate>
   <asp:LinkButton ID="lnkname" runat="server" Text='<%#Eval("Name") %>'
         PostBackUrl='<%#"~/Default.aspx?ID="+Eval("ID") %>'>
   </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>
Or You can do the above in the following ways by using Hyperlink.
<asp:HyperLinkField DataNavigateUrlFields="ID,Name,Location" 
DataNavigateUrlFormatString="Default.aspx?id={0}&name={1}&loc={2}" 
Text="Transfer values to other page" />
**********************************************************
If you don't want to show the header of the gridview then set the properties of gridview
ShowHeader="false" 
**********************************************************
Suppose you have a requirement that based on id value you want to update the row value but you are n't showing the value in the gridview. In that case use DataKeys property of gridview.
<asp:GridView Width="100%" ID="gdvShow" runat="server" 
         AutoGenerateColumns="false" AutoGenerateEditButton="True" 
        onrowcancelingedit="gdvdetailOfOtherbill_RowCancelingEdit" 
        onrowediting="gdvdetailOfOtherbill_RowEditing" 
        onrowupdating="gdvdetailOfOtherbill_RowUpdating" 
        onrowcreated="gdvdetailOfOtherbill_RowCreated" DataKeyNames="id,rowid">
In the row updating event of grid view write the code
int i1 = Convert.ToInt32(gdvShow.DataKeys[e.RowIndex].Values[0]);
int i2 = Convert.ToInt32(gdvShow.DataKeys[e.RowIndex].Values[1]);
Store the values in two variables and use where ever you want to update the row.
*********************************************************
Suppose you are trying to bind a gridview and in the backend there is no record in the table. You want to show some some message when the table has no record. Then set the property of gridview as following.
EmptyDataText="There is no record."
*********************************************************
Suppose you have a gridview and there is delete option in your gridview. You want to show some confirmation message when user click on delete button then do the following.
<asp.LinkButton ......... OnClientClick="return confirm('Are you sure you want               to delete this record ?');"
*********************************************************
If you want to show the footer information in your gridview then do the following.
1. Set the ShowFooter properties of gridview to true. Set FooterText="Total"
2. With in <columns> write the below line.
      <asp:TemplateField HeaderText="Footer">
       <ItemTemplate>
                 <asp:Label ID="lblAmount" runat="server" Text='<%#Eval("Amount")>'>             
      </asp:Label>
      </ItemTemplate>
      <FooterTemplate> 
            <asp:Label ID="lblTotal" runat="server"></asp:Label>
      </FooterTemplate>
      </asp:TemplateField>
     </Columns>
     <FooterStyle BackColor="#336699" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
     </asp:Gridview>
3. Write the code in the Gridview_rowdatabound of gridview.
   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
      decimal grdTotal = 0;
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        decimal rowTotal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));
        grdTotal = grdTotal + rowTotal;
      }    
      if (e.Row.RowType == DataControlRowType.Footer)
      {
         Label lbl = (Label)e.Row.FindControl("lblTotal");
         lbl.Text = grdTotal.ToString("c");
      }
   }


Sunday, 29 May 2011

DataTable - Adding, Modifying, Deleting, Filtering, Sorting rows & Reading/Writing from/to Xml

Creating a DataTable

To create a DataTable, you need to use System.Data namespace, generally when you create a new class or page, it is included by default by the Visual Studio. Lets write following code to create a DataTable object. Here, I have pased a string as the DataTable name while creating DataTable object.

// instantiate DataTable
DataTable dTable = new DataTable("Dynamically_Generated");



Creating Columns in the DataTable

To create column in the DataTable, you need to use DataColumn object. Instantiate the DataColumn object and pass column name and its data type as parameter. Then call add method of DataTable column and pass the DataColumn object as parameter.


// create columns for the DataTable
DataColumn auto = new DataColumn("AutoID", typeof(System.Int32));
dTable.Columns.Add(auto);
// create another column
DataColumn name = new DataColumn("Name", typeof(string));
dTable.Columns.Add(name);
// create one more column
DataColumn address = new DataColumn("Address", typeof(string));
dTable.Columns.Add(address);



Specifying AutoIncrement column in the DataTable

To specify a column as AutoIncrement (naturally it should be an integer type of field only), you need to set some properties of the column like AutoIncrement, AutoIncrementSeed. See the code below, here I am setting the first column "AutoID" as autoincrement field. Whenever a new row will be added its value will automatically increase by 1 as I am specified AutoIncrementSeed value as 1.


// specify it as auto increment field
auto.AutoIncrement = true;
auto.AutoIncrementSeed = 1;
auto.ReadOnly = true;
If you want a particular column to be a unique column ie. you don't want duplicate records into that column, then set its Unique property to true like below.
auto.Unique = true;



Specifying Primary Key column in the DataTable

To set the primary key column in the DataTable, you need to create arrays of column and store column you want as primary key for the DataTable and set its PrimaryKey property to the column arrays. See the code below.


// create primary key on this field
DataColumn[] pK = new DataColumn[1];
pK[0] = auto;
dTable.PrimaryKey = pK;
Till now we have created the DataTable, now lets populate the DataTable with some data.



Populating data into DataTable

There are two ways to populate DataTable.
Using DataRow object
Look at the code below, I have created a DataRow object above the loop and I am assiging its value to the dTable.NewRow() inside the loop. After specifying columns value, I am adding that row to the DataTable using dTable.Rows.Add method.


// populate the DataTable using DataRow object
DataRow row = null;
for (int i = 0; i < 5; i++)
{
     row = dTable.NewRow();
     row["AutoID"] = i + 1;
     row["Name"] = i + " - Ram";
     row["Address"] = "Ram Nagar, India - " + i;
     dTable.Rows.Add(row);
}

Instead of using the column name, you can use ColumnIndex too, however it is not suggested as you might want to add a column in the mid of the table then you will need to change your code wherever you have specified the index of the column. Same applies while reading or writing values into Database column. Asiging the value of column using Arrays In following code, I have specified the values of every column as the array separated by comma (,) in the Add method of the dTable.Rows.

 // manually adding rows using array of values
 dTable.Rows.Add(6, "Manual Data - 1", "Manual Address - 1, USA");
dTable.Rows.Add(7, "Manual Data - 2", "Manual Address - 2, USA");


Modifying data into DataTable


Modifying Row Data To edit the data of the row, sets its column value using row index or by specifying the column name. In below example, I am updating the 3rd row of the DataTable as I have specified the row index as 2 (dTable.Rows[2]).

 // modify certain values into the DataTable
dTable.Rows[2]["AutoID"] = 20;
dTable.Rows[2]["Name"] = "Modified";
dTable.Rows[2]["Address"] = "Modified Address";
dTable.AcceptChanges();


Deleting Row


To delete a row into DataTable, call the rows.Delete() method followed by AcceptChanges() method. AcceptChanges() method commits all the changes made by you to the DataTable. Here Row[1] is the index of the row, in this case 2nd row will be deleted as in collection (here rows collection) count start from 0.

// Delete row
 dTable.Rows[1].Delete();
dTable.AcceptChanges();


Filtering data from DataTable

To filter records from the DataTable, use Select method and pass necessary filter expression. In below code, the 1st line will simply filter all rows whose AutoID value is greater than 5. The 2nd line of the code filters the DataTable whose AutoID value is greater than 5 after sorting it.

DataRow[] rows = dTable.Select(" AutoID > 5");
DataRow[] rows1 = dTable.Select(" AutoID > 5", "AuotID ASC");

Note that Select method of the DataTable returns the array of rows that matche the filter expression. If you want to loop through all the filtered rows, you can use foreach loop as shown below. In this code, I am adding all the filtered rows into another DataTable.

foreach (DataRow thisRow in rows)
{
// add values into the datatable
dTable1.Rows.Add(thisRow.ItemArray);
}

Working with Aggregate functions 

We can use almost all aggregate functions with DataTable, however the syntax is bit different than standard SQL.
Suppose we need to get the maximum value of a particular column, we can get it in the following way.

DataRow[] rows22 = dTable.Select("AutoID = max(AutoID)");
string str = "MaxAutoID: " + rows22[0]["AutoID"].ToString();

To get the sum of a particular column, we can use Compute method of the DataTable. Compute method of the DataTable takes two argument. The first argument is the expression to compute and second is the filter to limit the rows that evaluate in the expression. If we don't want any filteration (if we need only the sum of the AutoID column for all rows), we can leave the second parameter as blank ("").

object objSum = dTable.Compute("sum(AutoID)", "AutoID > 7");
string sum = "Sum: " + objSum.ToString();
// To get sum of AutoID for all rows of the DataTable
object objSum = dTable.Compute("sum(AutoID)", "");



Sorting data of DataTable

Oops !. There is no direct way of sorting DataTable rows like filtering (Select method to filter DataRows).
There are two ways you can do this.

Using DataView
See the code below. I have created a DataView object by passing my DataTable as parameter, so my DataView will have all the data of the DataTable. Now, simply call the Sort method of the DataView and pass the sort expression. Your DataView object have sorted records now, You can either directly specify the Source of the Data controls object like GridView, DataList to bind the data or if you need to loop through its data you can use ForEach loop as below.

// Sorting DataTable
DataView dataView = new DataView(dTable);
dataView.Sort = " AutoID DESC, Name DESC";
foreach (DataRowView view in dataView)
{
Response.Write(view["Address"].ToString());
}

Using DataTable.Select() method
Yes, you can sort all the rows using Select method too provided you have not specified any filter expression. If you will specify the filter expression, ofcourse your rows will be sorted but filter will also be applied. A small drawback of this way of sorting is that it will return array of DataRows as descibed earlier so if you are planning to bind it to the Data controls like GridView or DataList you will have for form a DataTable by looping through because directly binding arrays of rows to the Data controls will not give desired results.

DataRow[] rows = dTable.Select("", "AutoID DESC");
Writing and Reading XmlSchema of the DataTable
If you need XmlSchema of the DataTabe, you can use WriteXmlSchema to write and ReadXmlSchema to read it. There are several overloads methods of both methods and you can pass filename, stream, TextReader, XmlReader etc. as the parameter. In this code, the schema will be written to the .xml file and will be read from there.

// creating schema definition of the DataTable
dTable.WriteXmlSchema(Server.MapPath("~/DataTableSchema.xml"));
// Reading XmlSchema from the xml file we just created
DataTable dTableXmlSchema = new DataTable();
dTableXmlSchema.ReadXmlSchema(Server.MapPath("~/DataTableSchema.xml"));



Reading/Writing from/to Xml

If you have a scenario, where you need to write the data of the DataTable into xml format, you can use WriteXml method of the DataTable. Note that WriteXml method will not work if you will not specify the name of the DataTable object while creating it. Look at the first code block above, I have passed "Dynamically_Generated" string while creating the instance of the DataTable. If you will not specify the name of the DataTable then you will get error as WriteXml method will not be able to serialize the data without it.

// Note: In order to write the DataTable into XML,
// you must define the name of the DataTable while creating it
// Also if you are planning to read back this XML into DataTable, you should define the   XmlWriteMode.WriteSchema too
// Otherwise ReadXml method will not understand simple xml file
dTable.WriteXml(Server.MapPath("~/DataTable.xml"), XmlWriteMode.WriteSchema);
// Loading Data from XML into DataTable
DataTable dTableXml = new DataTable();
dTableXml.ReadXml(Server.MapPath("~/DataTable.xml"));

If you are planning to read the xml you have just created into the DataTable sometime later then you need to specify XmlWriteMode.WriteSchema too as the 2nd parameter while calling WriteXml method of the DataTable otherwise normally WriteXml method doesn't write schema of the DataTable. In the abscence of the schema, you will get error (DataTable does not support schema inference from Xml) while calling ReadXml method of the DataTable.

Saturday, 28 May 2011

Store XML data into database using stored procedure :


XML variables in SQL Server 2005 make it easy to "shred" XML strings into relational data. The main new methods you'll need to use are value() and nodes() which allow us to select values from XML documents.


DECLARE @productIds xml
SET @productIds ='<Products><id>3</id><id>6</id><id>15</id></Products>'

SELECT
ParamValues.ID.value('.','VARCHAR(20)')
FROM @productIds.nodes('/Products/id') as ParamValues(ID)

Which gives us the following three rows:
3
6
15

Here's a proc which takes a single XML parameter. We first declare a table variable (@Products) and load the XML values into it. Once that's done, we can join against the @Products table as if it were any other table in the database.

Alter PROCEDURE SelectByIdList(@productIds xml) AS
begin
DECLARE @Products TABLE (ID int)

INSERT INTO @Products (ID) SELECT ParamValues.ID.value('.','VARCHAR(20)')
FROM @productIds.nodes('/Products/id') as ParamValues(ID)
select * from @Products
end

To test the stored procedure run the below command:

     EXEC SelectByIdList @productIds='<Products><id>3</id><id>6</id><id>15</id></Products>'

In the page:
//To create a xml file write the below code

public static string BuildXmlString(string xmlRootName, string[] values)
{
    StringBuilder xmlString = new StringBuilder();
    xmlString.AppendFormat("<{0}>", xmlRootName);
    for (int i = 0; i < values.Length; i++)
    {
    xmlString.AppendFormat("<value>{0}</value>", values[i]);
    }
    xmlString.AppendFormat("</{0}>", xmlRootName);
    return xmlString.ToString();
}