Monday, July 4, 2011

Converting or Accessing ItemSource as DataTabe from WPF DataGrid




// dataGrid1 of type DataGrid
DataTable dt = ((DataView)dataGrid1.ItemsSource).Table;


Sunday, July 3, 2011

Changing WPF C# DataGrid Column Width




DataGridColumn col = dataGrid1.Columns[0]; // first column
col.Width = 100; // change as per your requirement


Thursday, June 30, 2011

WPF C# DataGrid row background color




// do this in LoadingRow event
private void dataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Background = Brushes.Green; // set to background to green
}


Wednesday, June 29, 2011

WPF C# DataGrid Column Hide or Show





DataGridColumn col = dataGrid1.Columns[0]; // first column
col.Visibility = Visibility.Hidden; // hide
col.Visibility = Visibility.Visible; // show




Tuesday, June 28, 2011

Change background color of a dialog box in VC++ MFC





// .H file
class CMyDlg : public CDialogEx
{
COLORREF m_clrBk = RGB(255,255,200); // assign the color as per requirement
public:
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
};



// .CPP file
BEGIN_MESSAGE_MAP(CMyDlg, CDialogEx)
ON_WM_CTLCOLOR()
END_MESSAGE_MAP()

HBRUSH CMyDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
if(nCtlColor == CTLCOLOR_DLG) // remove if statement to change the background for all the controls
{
hbr = CreateSolidBrush(m_clrBk);
pDC->SetBkColor(m_clrBk);
}
return hbr;
}





Monday, June 27, 2011

WPF stop closing the window or cancelling from closing the window





void MyWPFWindow_Closing(object sender, CancelEventArgs e)
{
e.Cancel = true; // setting to true will not close the window
}




Sunday, June 26, 2011

WPF ShowDialog return value





void MyWPFWindow_Closing(object sender, CancelEventArgs e)
{
DialogResult = true; // or false based on your requirement
}

//Usage
MyWPFWindow wnd = new MyWPFWindow();
bool retvalue = wnd.ShowDialog();




Thursday, June 23, 2011

Mapping OleDbType with .Net Type



/***********************************************************************
/* Description: When dealing with excel files and it's data through .Net application it may require to compare the OLE datatypes(excel) and .net datatypes. Following code is compiled using VS2010 and C#.
***********************************************************************/




public static bool IsOleDBEqualToSystemType(TypeCode sysType, OleDbType oleType)
{
bool bRet = false;
switch (oleType)
{
case OleDbType.BigInt:
bRet = sysType == TypeCode.Int64;
break;
case OleDbType.Binary:
bRet = sysType == TypeCode.Byte;
break;
case OleDbType.Boolean:
bRet = sysType == TypeCode.Boolean;
break;
case OleDbType.BSTR:
bRet = sysType == TypeCode.String;
break;
case OleDbType.Char:
bRet = sysType == TypeCode.String;
break;
case OleDbType.Currency:
bRet = sysType == TypeCode.Decimal;
break;
case OleDbType.Date:
bRet = sysType == TypeCode.DateTime;
break;
case OleDbType.DBDate:
bRet = sysType == TypeCode.DateTime;
break;
case OleDbType.DBTime:
bRet = sysType == TypeCode.DateTime;
break;
case OleDbType.DBTimeStamp:
bRet = sysType == TypeCode.DateTime;
break;
case OleDbType.Decimal:
bRet = sysType == TypeCode.Decimal;
break;
case OleDbType.Double:
bRet = sysType == TypeCode.Double;
break;
case OleDbType.Integer:
bRet = sysType == TypeCode.Int32;
break;
case OleDbType.LongVarChar:
bRet = sysType == TypeCode.String;
break;
case OleDbType.LongVarWChar:
bRet = sysType == TypeCode.String;
break;
case OleDbType.Numeric:
bRet = sysType == TypeCode.Decimal;
break;
case OleDbType.Single:
bRet = sysType == TypeCode.Single;
break;
case OleDbType.SmallInt:
bRet = sysType == TypeCode.UInt16;
break;
case OleDbType.TinyInt:
bRet = sysType == TypeCode.SByte;
break;
case OleDbType.UnsignedBigInt:
bRet = sysType == TypeCode.UInt64;
break;
case OleDbType.UnsignedInt:
bRet = sysType == TypeCode.UInt32;
break;
case OleDbType.UnsignedSmallInt:
bRet = sysType == TypeCode.UInt16;
break;
case OleDbType.UnsignedTinyInt:
bRet = sysType == TypeCode.Byte;
break;
case OleDbType.VarChar:
bRet = sysType == TypeCode.String;
break;
case OleDbType.VarNumeric:
bRet = sysType == TypeCode.Decimal;
break;
case OleDbType.VarWChar:
bRet = sysType == TypeCode.String;
break;
case OleDbType.WChar:
bRet = sysType == TypeCode.String;
break;
}
return bRet;
}

Follow the link "http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbtype(v=vs.71).aspx" for more details





Sunday, June 19, 2011

Get Column Names And Data Types from the Database without reading the data



/***********************************************************************
/* Description: Extracting column details from the excel book is as good as reading the details from MS-Access MDB file. Following code demonstrates the procedure. Same procedure can be followed for MDB file also just by changing the connection string.
This code is compiled in VS2010, C#.
***********************************************************************/




OleDbConnection conn = new OleDbConnection("Provider= Microsoft.Jet. OLEDB.4.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 8.0");
string strSheetName = GetExcelSheetNames(txtFileName.Text)[0];
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns,
new object[] { null, null, strSheetName, null });

OleDbType[] exColTypes = new OleDbType[dt.Rows.Count];
string[] exColNames = new string[dt.Rows.Count];

foreach (DataRow row in dt.Rows)
{
int nColIndex = Convert.ToInt32(row[6]);
exColTypes[nColIndex - 1] = (OleDbType)row[11];
exColNames[nColIndex - 1] = row[3].ToString();
}

conn.Close();





Thursday, March 24, 2011

Accessing the DataGridRow from WPF DataGrid



/***********************************************************************
/* Description: Accessing the DataGridRow from WPF DataGrid by row index */
***********************************************************************/




DataGridRow dgr = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(nRowIndex);
if (dgr == null) // row might be invisible (top / bottom). So, scroll into the view and get it
{
dataGrid1.UpdateLayout();
dataGrid1.ScrollIntoView(dataGrid1.Items[nRowIndex]);
dgr = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(nRowIndex);
}




Wednesday, March 23, 2011

Get All Sheet Names From Excel File with C# and ADO.NET



/***********************************************************************
Description:Dealing with excel files using ADO.NET is as good as dealing with ms-access databases. Here is the code for getting all the sheet names from the given excel file. Each worksheet can be assumed as a table in database. Change the extended properties in the connection string to deal with various verions of excel files.
This code is compiled in the environment C#, VS2010, .NET 4.0.
***********************************************************************/




public string[] GetExcelSheetNames(string excelFileName)
{
OleDbConnection con = null;
DataTable dt = null;
String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
con = new OleDbConnection(conStr);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}





Monday, February 28, 2011

A simplae FTP client application



/***********************************************************************
Description:Use the following function to transfer all the files from your local drive to ftp server. This code is compiled using VS 2010, VC++ and MFC.

***********************************************************************/




#include "afxinet.h"
#include <windows.h>
#include <iostream>

CString _strServerName;    // your ftp server
CString _strUserName;    // ftp server user name
CString _strPassword;    // ftp server password
CString _strLocalPath;    // local folder path
CString _strRemotePath;    // remote folder path

void StartTransfer()
{
    CInternetSession inetSession;
    CFtpConnection* pFtp = inetSession.GetFtpConnection(_strServerName,_strUserName,_strPassword);
    if(pFtp != NULL)
    {
        cout << "FTP server opened successfully...\n";
    }
    else
    {
        cout << "FTP server could not open...\n";
        return;
    }

    if(!pFtp->SetCurrentDirectory(_strRemotePath))
    {
        cout << "Remote path doesn't exist\n";
        pFtp->Close();
        return;
    }
    CFileFind fileFind;
    if(!SetCurrentDirectory(_strLocalPath))
    {
        cout << "Local path could not find...\n";
        pFtp->Close();
        return;
    }

    BYTE pBuff[1000];
    CString str;
    if(fileFind.FindFile(NULL))
    {
        while(1)
        {
            BOOL bFound = fileFind.FindNextFile();
            CString strFileName = fileFind.GetFileName();
            CFile file;
            if(file.Open(strFileName,CFile::modeRead))
            {
                CInternetFile* pFtpFile = pFtp->OpenFile(strFileName,GENERIC_WRITE);
                UINT uiLength = file.GetLength();
                int nFrameSize = 1000;
                UINT uiTransferred = 0;
                int nReadBytes = 0;
                wcout << (LPCTSTR)(fileFind.GetFileName() + CString(" transfer started..."));
                CONSOLE_SCREEN_BUFFER_INFO ConsoleCursorInfo;
                GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&ConsoleCursorInfo);
                CString strPer = L"%";
                while((nReadBytes = file.Read(pBuff,nFrameSize)) == nFrameSize)
                {
                    pFtpFile->Write(pBuff,nFrameSize);
                    uiTransferred += nFrameSize;
                    str.Format(L"%.1f%s",((double)uiTransferred * 100.0) / (double)uiLength,strPer);
                    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),ConsoleCursorInfo.dwCursorPosition);
                    wcout << (LPCTSTR)str;
                }

                if(nReadBytes > 0)
                {
                    pFtpFile->Write(pBuff,nReadBytes);
                }
                uiTransferred += nReadBytes;
                str.Format(L"%.1f%s",100.0,strPer);
                SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),ConsoleCursorInfo.dwCursorPosition);
                wcout << (LPCTSTR)str;

                if(uiTransferred == uiLength)
                {
                    wcout << (LPCTSTR)(CString("\n") + fileFind.GetFileName() + CString(" transfer success\n"));
                }
                else
                {
                    wcout << (LPCTSTR)(CString("\n") + fileFind.GetFileName() + CString(" transfer fail\n"));
                }
                file.Close();
                pFtpFile->Close();
            }
            if(!bFound) break;
        }
    }
    inetSession.Close();
}





Monday, January 31, 2011

Setting Values To RDLC Report



/***********************************************************************
Description:Following proceduce explains setting the values to controls such as textboxes in a RDLC report file. This code is compiled in C#, VS2010.
Step 1 : Create a parameter using Report Data window from Visual Studio 2010 (View -> Report Data)
Step 2 : Attach created parameter to a textbox in rdlc report (in design view)
Step 3 : Use the following code example

***********************************************************************/




ReportViewer repViewer = new ReportViewer();
repViewer.ProcessingMode = ProcessingMode.Local;
repViewer.LocalReport.ReportPath = @"YourReport.rdlc";
List par = new List();
ReportParameter p = new ReportParameter("Name","Your Name");
par.Add(p);
p = new ReportParameter("Address", "Hyderabad, India");
par.Add(p);
p = new ReportParameter("SrNo", "1000");
par.Add(p);
repViewer.LocalReport.SetParameters(par);