Friday, 28 December 2012

Find a folder with Visual Studio project

 In the Solution Explorer right-click on the solution name and select "Open folder in windows explorer"

Check internet connection

System.Net.WebClient   //Name space

Solutions 1:  
Public Void InternetConnCheck()
{     
     try
     { 
        WebClient Client=new WebClient ();
       Using (var stream = client.OpenRead("http://www.google.com")
       {       
           Messagebox.show("Connection is Open"); 
       }
     catch
     {
          Messagebox.show("Connection Not available");  
     }   

}

Solutions 2: 

Public Void InternetConnCheck()
{     
     try 
     {       
       System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
               Messagebox.show("Connection available");        
     }
     catch
     { 
        Messagebox.show("Connection Not available"); 
     }  

}

Solutions 3: 
bool InternetConnection = new Ping().Send
                          ("www.google.co.in").Status == IPStatus.Success;

Thursday, 27 December 2012

Check database connection is open or close

Solutions 1: 
OledbConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\test.mdb";
OleDbConnection Conn = new OleDbConnection(OledbConnString);
if (Conn.State == Conn.Open)
{
     Messagebox.show("Connection is Open");
}
else
{
     Messagebox.show("Connection is Close");
}

Tuesday, 25 December 2012

How to install East Asian language in Windows XP without CD

Solutions 1:   
1.  Download East Asian Language pack and extract files to a local folder  
2. Go to Start menu
3. Click Run
4.  Type"intl.cpl" and click OK
5. Choose tab “Languages”
6. check the “Install files for East Asian languages".

7. Choose Extract File Path
8. Choose "XJIS.NL_"

9.  Reboot System
10.  Repeat step 2,3,4,5
11. Click button “Details”.


12.Click button “Add”

13. You will see “Add Input Language” dialogue box. Choose “Korean” from dropdownlist.
14. You will see in “Korean” language part, the keyboard part is now has “Korean”. 
15. Click on the language to choose different input. You will see there are two input services. KO for Korean, and EN for English. Choose “Korean”.

Monday, 24 December 2012

DataGridView Search & Focusing a Search row

Solutions 1:    
private void button1_Click(object sender, EventArgs e)
{
            dataGridView1.ClearSelection();
            String searchValue = textBox1.Text;  //Textbox1 -> Search Key Word
            int rowIndex = -1;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells[1].Value != null)
                {
                    if (row.Cells[1].Value.ToString().ToLower().Equals(searchValue.ToLower()))
                    {
                        rowIndex = row.Index;                       
                        dataGridView1.Rows[rowIndex].Selected = true;
                        dataGridView1.FirstDisplayedScrollingRowIndex = rowIndex;                       
                        break;
                    }
                }
            }
        }


Null before ToString() Checking

Solutions 1:   
if (entry.Properties["something"].Value != null) 
{ 
}

Thursday, 20 December 2012

Get the field names of a MS access database table

Solutions : 
using System.Data.OleDb;  //namespace


OledbConnString="Provider=Microsoft.Jet.OLEDB.4.0; Data Source="C:\\dbBCR.mdb";
            OleDbConnection Conn = new OleDbConnection(OledbConnString);
            Conn.Open();
            OleDbCommand Command = new OleDbCommand("select * from Table1", Conn);
            OleDbDataReader reader = Command.ExecuteReader();
            DataTable schemaTable = reader.GetSchemaTable();
                        foreach (DataRow row in schemaTable.Rows)
            {
                  MessageBox.Show(row.Field<string>("ColumnName"));
             }
            Conn.Close();

Get Excel Sheet Name


using Excel = Microsoft.Office.Interop.Excel;   //namespace
Excel.Application sExcelApp;
Excel.Workbook sWorkbook;
 


Solutions 1: 

               sExcelApp.Visible = false;
            sWorkbook = sExcelApp.Workbooks.Open(sFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  //sFilePath  Excel File Path
            foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in sWorkbook.Worksheets)
            {
                Messagebox.show(wSheet.Name.ToString());
            }


Solutions 2:


DataSet ds = new DataSet();
            OleDbCommand excelCommand = new OleDbCommand(); OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
           String excelConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + sFilePath + "; Extended Properties=Excel 8.0;"; 

//get "sFilePath" Excel Path
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
            excelConn.Open();
            dtPatterns = new DataTable();
            DataTable dtsheet = new DataTable();
            dtsheet = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string ExcelSheetName = dtsheet.Rows[0]["Table_Name"].ToString();
    //get First Excel Sheet Name

Excel Sheet Column Names



using Excel = Microsoft.Office.Interop.Excel;   //namespace
Excel.Application sExcelApp;
Excel.Workbook sWorkbook;
 


Solutions 1: 
sExcelApp = new Microsoft.Office.Interop.Excel.Application();
sWorkbook = sExcelApp.Workbooks.Open(sFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);  //sFilePath  Excel File Path
            Excel.Worksheet workSheet = (Excel.Worksheet)sWorkbook.Worksheets.get_Item(XlSheetNo);  //Sheet No (sheet1=1 / sheet2=2)
            Excel.Range range = workSheet.UsedRange;
            for (int i = 1; i <= range.Columns.Count; i++)
            {
                this.Invoke(new MethodInvoker(delegate()
                {
                    listBox1.Items.Add(((Excel.Range)range.Cells[1, i]).Value2);
                }));
            }

Solutions 2:

using System.Data.Oldeb; //namespace

OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
            connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            connectionStringBuilder.DataSource = sFilePath;
            connectionStringBuilder.Add("Mode", "Read");

            const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
            connectionStringBuilder.Add("Extended Properties", extendedProperties);

           
            using (OleDbConnection connection = new OleDbConnection(connectionStringBuilder.ToString()))           
            {
                connection.Open();
                OleDbDataAdapter Oapter = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection);
                oDataSet = new DataSet();
                Oapter.Fill(oDataSet);
                DataTable dt = (oDataSet.Tables[0]);
                foreach (DataTable table in oDataSet.Tables)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        this.Invoke(new MethodInvoker(delegate()
                        {
                            listBox1.Items.Add(column.ColumnName.ToString());
                        }));
                    }
                }
                connection.Close();
            }
 

Monday, 17 December 2012

Convert Time to integer to Time

Solutions : (Convert Time to Integer)
    Formula A1 (Cell No)*1440











Solutions : (Convert Integer to Time)

Formula A1
=INT(A1/60)&":"& A1-INT(A1/60)*60





Friday, 14 December 2012

Displaying Row Numbers in a DataGrid Row Header



Solutions : 
using System.Drawing;
private void gridviewAll_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
             Font drawFont = new Font("Arial", 10);   
            e.Graphics.DrawString((e.RowIndex + 1).ToString(), drawFont, SystemBrushes.ControlText,    
                 e.RowBounds.Location.X + 15, e.RowBounds.Location.Y);
 }

Hide DataGrid row headers




Solutions 1: 
Coding part:

dataGridView1.RowHeadersVisible = false;


Solutions 2: 
Without Coding:


Excel Heders collected using OLEDB

string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
                                      Data Source=" + fileName + @";Extended Properties=""Excel 8.0;HDR=NO;""";
string CreateCommand = "SELECT * FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand(CreateCommand, conn);
//   cmd.ExecuteNonQuery();
DbDataReader dr= cmd.ExecuteReader();
int i = 0;
while (dr.Read())
{
    string ab = dr.GetValue(i).ToString();
    MessageBox.Show(ab);
    i++;
}

Dynamically Add Collapsible Panel Extender from code behind c#

protected void Page_Load(object sender, EventArgs e)
{
CollapsiblePanelExtender collapsiblePanelExtender = new CollapsiblePanelExtender();
collapsiblePanelExtender.TargetControlID = this.ContentPanel.ID; //your panel id
collapsiblePanelExtender.ExpandControlID = this.LinkButton.ID;//your link button id
 collapsiblePanelExtender.CollapseControlID = this.LinkButton.ID;
//your panel id collapsiblePanelExtender.ScrollContents = false;
collapsiblePanelExtender.Collapsed = false;
collapsiblePanelExtender.ExpandDirection =CollapsiblePanelExpandDirection.Vertical;
collapsiblePanelExtender.SuppressPostBack = true;
collapsiblePanelExtender.TextLabelID = this.TextLabel.ID; //your label id
collapsiblePanelExtender.CollapsedText = "Collapsed";
collapsiblePanelExtender.ExpandedText = "Opended";
//the name of panel that containt CollapsiblePanelExtender
 this.panelExtenderContainer.Controls.Add(collapsiblePanelExtender);
}

Wednesday, 12 December 2012

Test SQL Server connection use C#

Solutions:   
 
SqlConnection oConnection = new SqlConnection("user id='Usename';password='Password ';Data Source='Sql servername ';Trusted_Connection=yes;");
            try
            {
                oConnection.Open();
                Messagebox("SQL connection test successfully");
             }
            catch (Exception test)
            {
                Messagebox("SQL connection problem");
            }
            finally
            {
                oConnection.Close();
            } 

Monday, 10 December 2012

How do put text on ProgressBar?

Display Custom Text

using (Graphics gr = progressBar1.CreateGraphics())
{
     string sString="Progress Bar Visible";
     Brush b = new SolidBrush( Color.Red);
     StringFormat sf = new StringFormat( StringFormatFlags.NoWrap );
     sf.Alignment = StringAlignment.Center;
     gr.DrawString(sString, new Font("Arial", 12.0f,FontStyle.Bold), b,  progressBar1.ClientRectangle, sf);
     gr.Dispose();
     b.Dispose();
     sf.Dispose();
}

Add the Percent  into a Standard Progress Bar Control

 
int percent = (int)(((double)(progressBar1.Value - progressBar1.Minimum) /
(double)(progressBar1.Maximum - progressBar1.Minimum)) * 100);
using (Graphics gr = progressBar1.CreateGraphics())
{
    gr.DrawString(percent.ToString() + "%",
        SystemFonts.DefaultFont,
        Brushes.Black,
        new PointF(progressBar1.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
            SystemFonts.DefaultFont).Width / 2.0F),
        progressBar1.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
            SystemFonts.DefaultFont).Height / 2.0F)));
}
 
Download Sample Coding (Progress bar.rar) 

Saturday, 8 December 2012

Run Excel Macro from C#.net

using Excel = Microsoft.Office.Interop.Excel;
using VBIDE = Microsoft.Vbe.Interop;
using Office = Microsoft.Office.Core;

object misValue = System.Reflection.Missing.Value;
Object oMissing = System.Reflection.Missing.Value;

public void AddMacro()
{
    savepath = @"C:\Temp_999.xls";
    Excel.Application oExcel;
    Excel.Workbook oBook;
    VBIDE.VBComponent oModule;
    Office.CommandBar oCommandBar;
    Office.CommandBarButton oCommandBarButton;              
    oExcel = new Excel.Application();
    if (oExcel != null)
    {
        oBook = oExcel.Workbooks.Add(oMissing);
        oModule = oBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
        sCode = "<add your Macro Code>";
        oModule.CodeModule.AddFromString(sCode.Replace("'", "\""));
        oCommandBar = oExcel.CommandBars.Add("VBAMacroCommandBar", oMissing, oMissing, oMissing);
        oCommandBar.Visible = false;
        oCommandBarButton = (Office.CommandBarButton)oCommandBar.Controls.Add(Office.MsoControlType.msoControlButton, oMissing, oMissing, oMissing, oMissing);
        oCommandBarButton.OnAction = "VBAMacro";
        oCommandBarButton.Caption = "Call VBAMacro";
        oCommandBarButton.FaceId = 2151;
        oExcel.DisplayAlerts = false;
        oBook.SaveAs(savepath.ToString(), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);       
        RunMacro();
     }
     public void RunMacro()    
     {
         Excel.ApplicationClass oExcel1 = new Excel.ApplicationClass();
        oExcel1.Visible = false;
        Excel.Workbooks oBooks1 = oExcel1.Workbooks;
        Excel._Workbook oBook1 = null;
        oBook1 = oBooks1.Open(savepath, oMissing, oMissing,oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
        RunMacro1(oExcel1, new Object[] { "Combineallworkbooksintosingleworkbook" });           
        Microsoft.Office.Interop.Excel.Application oExcelApp;
        VBIDE.VBComponent module;
        oExcelApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        oExcelApp.DisplayAlerts = false;
        module = oExcelApp.ActiveWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
        module.CodeModule.AddFromString(sCode.Replace("'", "\""));
        string date = DateTime.Now.ToString().Replace("/", "-").Replace(":", ".");   
        spath1 = "Excel_Combined_" + date + ".xls";
        spath = txtSaveas.Text + "\\" + spath1;
        oExcelApp.ActiveWorkbook.SaveAs(spath.ToString(), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);   
       oExcelApp = null;
     }
     private void RunMacro1(object oApp, object[] oRunArgs)
     {
                 oApp.GetType().InvokeMember("Run",System.Reflection.BindingFlags.Default |System.Reflection.BindingFlags.InvokeMethod,null, oApp, oRunArgs);
      }   
}

Wednesday, 5 December 2012

Uninstalling program using C#.

Solutions:          using System.Diagnostics; // use name space                     
             Process process = new Process();
             process.Start("msiexec /x {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}");     
 where xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx represents GUID of that application that you want to uninstall.
 



 

Run to the other exe



Solutions:          using System.Diagnostics; // use name space
                        string str = Application.StartupPath + "\\SaveAsPDFandXPS.exe";
            Process process = new Process();
            process.StartInfo.FileName = str;
            process.Start();    

How to get startup path



Solutions:  Application.StartupPath