Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Tuesday, August 12, 2014

How to add TreeViewItem dynamically in TreeView control in WPF?

How to add TreeViewItem dynamically in TreeView control in WPF. Here is the coding example given below to add TreeViewItem in TreeView control.


public TreeViewItem CreateTreeViewItem(string nodeName, string headerText, string frontImagePath, string tailImagePath, bool isCheckBoxRequired)
        {
            TreeViewItem treeViewItem = new TreeViewItem();
            try
            {
                StackPanel stackPanel = new StackPanel();
                Label lblHeaderText = new Label();
                Image imgFrontIcon, imgTailIcon;
                imgFrontIcon = new Image(); imgTailIcon = new Image();

                stackPanel.Orientation = Orientation.Horizontal;
                if (isCheckBoxRequired)
                {
                    CheckBox chkbox = new CheckBox();
                    chkbox.Name = IDPrefixForControls.Chk_.ToString() + nodeName;
                    chkbox.HorizontalAlignment = HorizontalAlignment.Center;
                    chkbox.VerticalAlignment = VerticalAlignment.Center;
                    stackPanel.Children.Add(chkbox);
                }
                if (frontImagePath != null && frontImagePath != string.Empty)
                {
                    Uri uri = new Uri(ConstantVariables.UriString + frontImagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    imgFrontIcon.Source = bitMapSource;
                }
                if (tailImagePath != null && tailImagePath != string.Empty)
                {
                    Uri uri = new Uri(ConstantVariables.UriString + tailImagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    imgTailIcon.Source = bitMapSource;
                }
                lblHeaderText.Content = headerText;
                stackPanel.Children.Add(imgFrontIcon);
                stackPanel.Children.Add(lblHeaderText);
                stackPanel.Children.Add(imgTailIcon);
                nodeName = nodeName.Replace("-", "_").Replace(" ", "_");
                treeViewItem.Name = nodeName;
                treeViewItem.Header = stackPanel;
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
            return treeViewItem;
        }

Add Image column in Datagrid control dynamically in WPF

Here is the code example given to add Image column in Datagrid control dynamically at run time in WPF.

public void AddColumnsToDataGrid(DataGrid dataGrid, DataGridColumnType columnType, string headerText, string bindingName, string imagePath,
           )
        {
FrameworkElementFactory factoryElementStackPanelImages = AddMultipleImagesIntoOneColumn(imagePath);
                            DataTemplate dataTemplate = new DataTemplate();
                            dataTemplate.VisualTree = factoryElementStackPanelImages;

                            DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
                            dgTemplateColumn.Header = headerText;
                            dgTemplateColumn.CellTemplate = dataTemplate;
                            dgTemplateColumn.CellStyle = styleDataGridCell;
                            dataGrid.Columns.Add(dgTemplateColumn);
}

private FrameworkElementFactory AddMultipleImagesIntoOneColumn(string imagesSourcePath)
        {
            FrameworkElementFactory factoryElementStackPanel = new FrameworkElementFactory(typeof(StackPanel));
            try
            {
                string imagePath, imageName;
                factoryElementStackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
                FrameworkElementFactory factoryImage;
                if (imagesSourcePath.Contains(ConstantVariables.CharacterValueHash))
                {
                    string[] arrImageSource = imagesSourcePath.Split(Convert.ToChar(ConstantVariables.CharacterValueHash));
                    foreach (string imgSource in arrImageSource)
                    {
                        if (imgSource.Contains(ConstantVariables.CharacterValueDollar))
                        {
                            string[] arrImagePathNName = imgSource.Split(Convert.ToChar(ConstantVariables.CharacterValueDollar));
                            imagePath = arrImagePathNName[0];
                            imageName = arrImagePathNName[1];
                        }
                        else
                        {
                            imagePath = imgSource;
                            imageName = string.Empty;
                        }
                        Uri uri = new Uri(ConstantVariables.UriString + imagePath);
                        BitmapImage bitMapSource = new BitmapImage();
                        bitMapSource.BeginInit();
                        bitMapSource.UriSource = uri;
                        bitMapSource.EndInit();
                        factoryImage = new FrameworkElementFactory(typeof(Image));
                        factoryImage.SetValue(Image.SourceProperty, bitMapSource);
                        factoryImage.SetValue(Image.WidthProperty, 15d);
                        factoryImage.SetValue(Image.HeightProperty, 15d);
                        factoryImage.SetValue(Image.MarginProperty, new Thickness(1));
                        if (!imageName.Equals(string.Empty))
                        {
                            factoryImage.SetValue(Image.NameProperty, imageName);
                            factoryImage.SetValue(Image.ToolTipProperty, imageName);
                        }
                        factoryElementStackPanel.AppendChild(factoryImage);
                        ImageColumnElement.Add(factoryImage);
                    }
                }
                else
                {
                    if (imagesSourcePath.Contains(ConstantVariables.CharacterValueDollar))
                    {
                        string[] arrImagePathNName = imagesSourcePath.Split(Convert.ToChar(ConstantVariables.CharacterValueDollar));
                        imagePath = arrImagePathNName[0];
                        imageName = arrImagePathNName[1];
                    }
                    else
                    {
                        imagePath = imagesSourcePath;
                        imageName = string.Empty;
                    }
                    Uri uri = new Uri(ConstantVariables.UriString + imagePath);
                    BitmapImage bitMapSource = new BitmapImage();
                    bitMapSource.BeginInit();
                    bitMapSource.UriSource = uri;
                    bitMapSource.EndInit();
                    factoryImage = new FrameworkElementFactory(typeof(Image));
                    factoryImage.SetValue(Image.SourceProperty, bitMapSource);
                    factoryImage.SetValue(Image.WidthProperty, 15d);
                    factoryImage.SetValue(Image.HeightProperty, 15d);
                    factoryImage.SetValue(Image.MarginProperty, new Thickness(1));

                    if (!imageName.Equals(string.Empty))
                    {
                        factoryImage.SetValue(Image.NameProperty, imageName);
                        factoryImage.SetValue(Image.ToolTipProperty, imageName);
                    }
                    factoryElementStackPanel.AppendChild(factoryImage);
                    ImageColumnElement.Add(factoryImage);
                }
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
            return factoryElementStackPanel;
        }


Adding of Checkbox Column in Datagrid control in WPF

Some times we need to add some controls in a container at run time. Here is the coding logic given to add CheckBox column in Datagrid control dynamically at run time. This code logic is in context with WPF. for winforms the some classes may differ.

Example :

DataGridTemplateColumn dgTemplateColumn = new DataGridTemplateColumn();
                            
                            dgTemplateColumn.Header = headerText;

                            FrameworkElementFactory factoryElementCheckBox = new FrameworkElementFactory(typeof(CheckBox));
                            factoryElementCheckBox.SetBinding(CheckBox.IsCheckedProperty, new System.Windows.Data.Binding(bindingName));
                            factoryElementCheckBox.SetValue(CheckBox.NameProperty, bindingName);
                            factoryElementCheckBox.SetValue(CheckBox.HorizontalAlignmentProperty, HorizontalAlignment.Left);
                            factoryElementCheckBox.SetValue(CheckBox.VerticalAlignmentProperty, VerticalAlignment.Center);

                            CheckBoxColumnElement.Add(factoryElementCheckBox);

                            DataTemplate dataTemplate = new DataTemplate();
                            dataTemplate.VisualTree = factoryElementCheckBox;
                            dgTemplateColumn.CellTemplate = dataTemplate;
                            dgTemplateColumn.IsReadOnly = isReadOnly;
                            dataGrid.Columns.Add(dgTemplateColumn);
                            

Wednesday, July 30, 2014

What is Collection in .Net?

Collection classes are the specialized classes for data storage and retrieval.

Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index etc. These classes create collection of objects of the Object class, which is the base class for all data types in C#.


Most of the times we get a requirement to store the multiple data. This can be done by using the Array which supports the data storage at different indexes created. An Array is a collection of multiple data at different indexes. However this is a form of strongly typed object, we can store information in array of same type of object. 

On the other hand Collections gives us the flexibility to store the data of different type of objects in it.

Namespace for collections: System.Collection
Various types of collections and their usage.


Class
Usage
ArrayList
It represents an ordered list of objects which can be retrieved by indexes.
An Arraylist is alternative to an Array. However unlike array you can Add, Remove the items from the list and can be retrieved by indexes. An ArrayList is not bound to any specific length
Hashtable
This collection can store the objects with a key assigned to it. Any data storage is in the form of key-value pair in Hashtable and the stored object can be retrieved by the key which is assigned to it.
Stack
It represents a last-in and first out collection of object. When the item is added to stack, it is called “pushing” the item and when it get removed, it is called as “popping” the item.
Queue
It represents a first-in and first out collection of object. When the item is added to stack, it is called “enqueue” the item and when it get removed, it is called as “dequeue” the item.
SortedList
A SortedList is a combination of an array and a Hashtable.
It uses a key as well as an index to access the items in a list. If you access the items using an index, it is an Arraylist and if you access the items using a key, it is a Hashtable. The collection of items is always sorted by the key value.

Tuesday, July 22, 2014

What is an Interface?

An Interface is a container which contains the signature of the methods within. This means it can have only the declarations of the method without their definition. An interface needs to implement on the Class and in the implementation process the definition has to be provided for all the methods declared inside the interface.

As C# does not support multiple inheritance of classes, but at the same time we can implement as many interface as required on a class. So in that manner we can get the different functionalities inside a class by implementing multiple interface.

What all an interface can contain?

    è Methods
    è Properties
    è Events
    è Indexers

By default the access modifier is “public” for all of its children. An interface does not allow private access modifier to any of its child.

Example:

//Interface declaration
public interface IDemo
{
     public string SumValue {get; set;}   //Property declaration
public void Add(int num1, int num2); //Method declaration
}

//Interface implementation on class Demo
class Demo : IDemo
{
public string SumValue {get; set;}
public void Add(int num1, int num2)  //Method Implementation
{
SumValue = num1+num2;
}
}

Allow single quotation in a string for Insert or update query in C#

While inserting the data into database from application sometimes we encounter with the error of single quotation exists in the input data. Single quotation is the special character used to hold the string value in database (SQL). Here is the simple technique by which we can insert the details with single quotation into the input data.

Code language C#.

public string AllowSingleQouteToInsertOrUpdate(string inputValue)
        {
            string outputValue = string.Empty;
            if ((inputValue.IndexOf("'", 0) > 0) || (inputValue.IndexOf("'", 0) == 0))
            { outputValue = inputValue.Replace("'", "''"); }
            else
            { outputValue = inputValue; }
            return outputValue;
        }

Friday, July 18, 2014

Download Excel file from ASP.Net in VB.Net

As a requirement to have result data in xls file from ASP.Net application for some reporting purpose, Here is the simple process to get the same output.

The sample code is provided below to download the records in the excel file in the same table format i.e data in each cell of the sheet. We assume to have huge amount of data in DataTable object and in same table format it is required to download in xls sheet.
To create a different cell of data here we have used the Html Table and its Row and Column concept.

Here is the code snippet in VB.Net language.

Protected Sub GenerateXls(ByVal fileName As String, ByVal dtData As DataTable)
        Try
            HttpContext.Current.Response.Clear()
            HttpContext.Current.Response.ContentType = "application/ms-excel"
            HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "")
            HttpContext.Current.Response.Flush()
            Dim colCount, rowCount As Integer
            HttpContext.Current.Response.Write("<Table>")
            HttpContext.Current.Response.Write("<TR>")

            For colCount = 0 To dtData.Columns.Count - 1
                HttpContext.Current.Response.Write("<TD>")
                HttpContext.Current.Response.Write(dtData.Columns(colCount).ColumnName.ToString())
                HttpContext.Current.Response.Write("</TD>")
            Next
            HttpContext.Current.Response.Write("</TR>")

            For rowCount = 0 To dtData.Rows.Count - 1
                HttpContext.Current.Response.Write("<TR>")
                For colCount = 0 To dtData.Columns.Count - 1
                    HttpContext.Current.Response.Write("<TD>")
                    HttpContext.Current.Response.Write(dtData.Rows(rowCount)(colCount).ToString())
                    HttpContext.Current.Response.Write("</TD>")
                Next
                HttpContext.Current.Response.Write("</TR>")
            Next
            HttpContext.Current.Response.Write("</Table>")
            HttpContext.Current.Response.End()

        Catch ex As Exception
        End Try        
    End Sub

Wednesday, September 4, 2013

Serialize the class object into XML

Sometimes there is requirement to convert/serialize an object into the XML format so that we can do some operation and manipulation based on the XML data. Here is the simple trick to convert the object data into XML format.

This piece of code will give you the result of Serialized XML by converting an object.

void SerializeXml<T>(string filePath, object objectToSerialize)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                xmlSerializer.Serialize(fs, objectToSerialize);
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {              
            }
        }

Serialize the Class object into XElement

If you have the requirement to convert object of data into the XElement form, then here is the solution for the same. the below piece of code will give output in the form of XElement by serializing the object of the class.
This method takes input as object and cast this with the class as of type "T" and returns the output into XElement format.

XElement ToXElement<T>(object objectToSerialize)
        {
            try
            {
                using (var memoryStream = new MemoryStream())
                {
                    using (TextWriter streamWriter = new StreamWriter(memoryStream))
                    {
                        var xmlSerializer = new XmlSerializer(typeof(T));
                        var xmlSerializerNamespace = new XmlSerializerNamespaces();
                       // To make namespace empty
                        xmlSerializerNamespace.Add(string.Empty, string.Empty);
                        xmlSerializer.Serialize(streamWriter, objectToSerialize, xmlSerializerNamespace);
                        xElement = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));  
                    }
                }
            }
            catch (Exception ex)
            {
                xElement = null;            
            }
            return xElement;
        }

Friday, April 5, 2013

Send XML data through web service as POST (Attachment)

By this piece of code in C# we can send the data to the web service as an attachment in the POST method.


                ASCIIEncoding encoding = new ASCIIEncoding();
                string postdata = "<Root><Info>Value</Info></Root>";
                byte[] data = encoding.GetBytes(postdata);
                Uri uri = new Uri("Your service url");
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(uri);
                myRequest.Method = "POST";
                myRequest.ContentType = "text/xml;charset=utf-8";
                myRequest.Timeout = 30000;
                NetworkCredential netCredentials = new NetworkCredential("Username", "Password");
                CredentialCache crendentials = new CredentialCache();
                crendentials.Add(uri, "Basic", netCredentials);
                myRequest.Credentials = crendentials;
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
           
// Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                // Get response

                using (HttpWebResponse response = myRequest.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream
                    System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    Stream objStream = response.GetResponseStream();
                    StreamReader objSR = new StreamReader(objStream, encode, true);
                    string sResponse = objSR.ReadToEnd();
                }

Thursday, March 7, 2013

Convert XML string into DataTable object


 public DataTable ConvertXMLIntoDataTable(string inputData)
        {
            DataTable dtDataConverted = null;
            try
            {              
                StringReader stringReader = new StringReader(inputData);
                DataSet dsData = new DataSet();
                dsData.ReadXml(stringReader);
                dtDataConverted = dsData.Tables[0];
            }
            catch (Exception ex)
            {  }
            return dtDataConverted;
        }

Convert Datatable object into XElement object


public XElement ConvertDataTableIntoXElement(DataTable dtData)
        {
            XElement xElementConverted = null;
            try
            {
                xElementConverted = new XElement("container");
                using (XmlWriter xmlWriter = xElementConverted.CreateWriter())
                { dtData.WriteXml(xmlWriter, System.Data.XmlWriteMode.WriteSchema, true); }
            }
            catch (Exception ex)
            {  }
            return xElementConverted;
        }

Wednesday, March 6, 2013

Basic RESTful service in WCF

operation contract in the interface for the WCF service

[OperationContract]
        [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Xml,
            ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = "/ValidateXMLData?inputData={inputData}")]
        string ValidateXMLData(string inputData);

In the .svc file do the implementation for the interface.

   public string ValidateXMLData(string inputData)
        {
            string validatedString=string.Empty;
            try
            {
                 XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(inputData);
                validatedString = inputData;
            }
            catch (Exception ex)
            { }
            return validatedString;
        }

service configuration in your web.Config file

<system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="MyService.Services.RestService">
        <endpoint address="XML"
                  behaviorConfiguration="restPoxBehavior"
                  binding="webHttpBinding"
                  contract="MyService.Contracts.IRestService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="restPoxBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

Thursday, February 16, 2012

Write XML Data Dynamically

public void WriteDataToXML(string filePath, string[] fieldsList, string[] fieldsValue)
{
try
{
if (fieldsList.Length.Equals(fieldsValue.Length))
{
int arrayLength = fieldsList.Length;
if (File.Exists(filePath))
{
XDocument xDocument;
xDocument = XDocument.Load(filePath);
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
xDocument.Element("Details").Add(dataElement);
xDocument.Save(filePath);
}
else
{
XElement rootElement = new XElement("Details");
XElement dataElement = new XElement("Data");
for (int count = 0; count < arrayLength; count++)
{
XElement element = new XElement(fieldsList[count], fieldsValue[count]);
dataElement.Add(element);
}
rootElement.Add(dataElement);
rootElement.Save(filePath);
}
}
}
catch (Exception ex) { }
}

Wednesday, April 27, 2011

Create XML file using LINQ

public void AddProductCategory(string filePath, string productCategory)
{
XDocument oXDoc;
try
{
if (File.Exists(filePath))
{
oXDoc = XDocument.Load(filePath);
oXDoc.Element("DataContent").Add(
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXDoc.Save(filePath);
}
else
{
XElement oXElmnt = new XElement("DataContent",
new XElement("Data",
new XElement("ID", Guid.NewGuid().ToString()),
new XElement("CategoryName", productCategory)
));
oXElmnt.Save(filePath);
}
}
catch (Exception ex) { }
}

Wednesday, June 30, 2010

Create Excel file with save Dialog in ASP.Net

DataTable will have the data to write into Excel file
fileName will be Excel file name with extension(.xls/.xlsx)

public void SaveExcelFile(string fileName, DataTable dtData)
{
try
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName + "");
HttpContext.Current.Response.Flush();
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Columns[colCount].ColumnName.ToString());
HttpContext.Current.Response.Write("\t");
}
for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
{
HttpContext.Current.Response.Write("\n");
for (int colCount = 0; colCount < dtData.Columns.Count; colCount++)
{
HttpContext.Current.Response.Write(dtData.Rows[rowCount][colCount].ToString());
HttpContext.Current.Response.Write("\t");
}

}
HttpContext.Current.Response.End();
}
catch (Exception ex)
{ }
}

Friday, February 19, 2010

Some C# Coding Standards Should follow

Coding standards


  • Ø                          Naming Convention
1.       Use Pascal casing for Class name, Methods, Properties etc
                  Public void DisplayName()
                   {
                    }

2.       Use Camel casing for variables
string customerName
Int customerId

3.       Don’t use Hungerian notation
 string m_sName;
Int nCount;


  • Ø                      Always use meaningful names for variables, properties, Methods etc.
Like:- string customerName
Avoid :- string cust_Name


  • Ø                   Do not use underscore ( _ ) for local variables

  •                          Prefix Boolean variables, properties and methods with “is” or similar prefixes.

Private bool isFinished;


  • Ø          Namespace names should follow the standard pattern

...


  • Ø                   File name should match with class name.

For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)


  • Ø               Always use Pascal casing in filename.


  • Ø             Don’t use variables like i,j in loop. Always use meaningful names

Wrong approach:
For(int i=0; i<10; i++)
{
}

Right approach:
For(int count=0; count<10; count++)
{
}

  • Ø                 Always put Comments for classes, functions, properties etc.

///Summary
/// description of class,methods
///created by : user
///created on : date
///last modified by : user
///last created on : date



Wednesday, February 17, 2010

Creating Excel Workbook using C#.net

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Exl = Microsoft.Office.Interop.Excel;

public class createExcel
{

//Excel Objects
        Exl.Application excel;
        Exl.Workbook workBook;
        Exl.Workbooks workBooks;
        Exl.Sheets sheets;
        Exl._Worksheet workSheet;
        Exl.Range range;
        Exl.Range rangeCells;



public createExcel()
{
InitializeExcelObjects();
}

public void InitializeExcelObjects()
        {
            excel = new Exl.Application();
            workBooks = excel.Workbooks;
            workBook = excel.Workbooks.Add(Type.Missing);

            //sheets = excel.Sheets;
            //wSheet = (Exl._Worksheet)(sheets[1]);
        }


private int ExcelTemplate(string fileName, DataTable dtData)
        {
            int nmReturn=0, nmSheetIndex=1, nmColumnCount=1;
            StringBuilder strBuild = new StringBuilder();
            string sheetName = string.Empty;
            try
            {
        
                sheetName = dtData.Rows[0][1].ToString();
                sheets = excel.Sheets;
                workSheet = ((Exl.Worksheet)sheets[nmSheetIndex]);
                workSheet.Name = sheetName;
                range = workSheet.Cells;
                rangeCells = workSheet.Cells;
                for (int rowCount = 0; rowCount < dtData.Rows.Count; rowCount++)
                {
                    if (!sheetName.Equals(dtData.Rows[rowCount][1].ToString()))
                    {
                        nmSheetIndex++;
                        sheetName = dtData.Rows[rowCount][1].ToString();
                        workSheet = ((Exl.Worksheet)sheets[nmSheetIndex]);
                        workSheet.Name = sheetName;
                        range = workSheet.Cells;
                        rangeCells = workSheet.Cells;
                        nmColumnCount = 1;
                    }
                        //workSheet.Columns.ColumnWidth = 50;
                        rangeCells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlLeft;
                        rangeCells[1, nmColumnCount] = dtData.Rows[rowCount][0].ToString();
                        nmColumnCount++;
                                   }
                string filePath = Application.StartupPath.ToString() + fileName;
                workBook.SaveAs(filePath, Exl.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Exl.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excel.Workbooks.Close();
                nmReturn++;
            }
            catch (Exception ex) { nmReturn = 0; }
            return nmReturn;
        }
}

Saturday, June 27, 2009

Dynamic DataTable in Asp.Net

DataTable myDt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myDt = new DataTable();
myDt = createDataTable();
Session["myDatatable"] = myDt;

this.GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
this.GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
addDataTableData();
populateGridView();
}

private DataTable createDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", Type.GetType("System.String"));
dt.Columns.Add("Name", Type.GetType("System.String"));
return dt;
}

private void populateGridView()
{
GridView1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
GridView1.DataBind();
}

private void addDataTableData()
{
DataTable myTable = ((DataTable)Session["myDatatable"]);
DataRow row;

row = myTable.NewRow();

row["id"] = TextBox1.Text;
row["Name"] = TextBox2.Text;

myTable.Rows.Add(row);
}

Motivational qoutes

पूरे विश्वास के साथ अपने सपनों की तरफ बढ़ें। वही ज़िन्दगी जियें जिसकी कल्पना आपने की है।