Monday, May 28, 2012

How to Read Remote PC file and Show in your PC window

Sometimes you may need to read a file which exists in Server PC and want to show in your Client PC. To make it simple Lets say i want to read an Excel file which exists in a remote machine and want to show in my client machine.

By following code we can do that easily.

FileInfo finfo = new FileInfo(@"\\192.168.100.20\D$\Leave information.xls");
bool exists = finfo.Exists;
 

if (finfo.Exists)
{
          System.Diagnostics.Process.Start(
finfo.FullName);
}

else
{
         MessageBox.Show("File Not Found");
}

// Here my remote PC address is 192.168.100.20 and The Excel file located in D drive 

You may place the above code into any button click event 


Thursday, December 15, 2011

Export DataGridView data into Excel Sheet Using C#

Sometimes you may need to Export Grid View data into Excel Sheet. Using following code u can do that.

using System.IO;

//------------------------- SAVE FILE OPTION -----------------------------
    string fileName = "";
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.CheckPathExists = true;
    saveFileDialog.AddExtension = true;
    saveFileDialog.ValidateNames = true;
    saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    saveFileDialog.DefaultExt = ".xls";
    saveFileDialog.Filter = "Microsoft Excel Workbook (*.xls)|*.xls";
//------------------------------------------------------------------------         

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                fileName = saveFileDialog.FileName;

                Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
                ExcelApp.Application.Workbooks.Add(Type.Missing);

                int rowCount = dataGridView1.Rows.Count;
                int colCount = dataGridView1.Columns.Count;

                // Storing header part in Excel
                for (int i = 1; i < colCount + 1; i++)
                {
                    ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
                }

                // Storing Each row and column value to excel sheet               
                for (int i = 0; i < rowCount; i++)
                {
                    this.Text = "Processing: " + dataGridView1.Rows[i].Cells[0].Value.ToString();
                    for (int j = 0; j < colCount; j++)
                    {
                        ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                    }
                }
                string fileLocation = fileName;

                if (File.Exists(fileLocation))
                {
                    try
                    {
                        File.Delete(fileLocation);
                        ExcelApp.ActiveWorkbook.SaveCopyAs(fileLocation);
                        ExcelApp.ActiveWorkbook.Saved = true;
                        ExcelApp.Quit();
                        MessageBox.Show("Excel file created-- " + fileLocation);
                    }
                    catch (IOException ioe)
                    {
                        MessageBox.Show("Close the Excel file and Export again...");
                    }
                }
                else
                {
                    ExcelApp.ActiveWorkbook.SaveCopyAs(fileLocation);
                    ExcelApp.ActiveWorkbook.Saved = true;
                    ExcelApp.Quit();

                    MessageBox.Show("Excel file created-- " + fileLocation);
                }
            }


You may need to 'ADD' Office reference into your project. By following steps you can add MS office reference. 
First click Project -> Add Reference


Then Go to COM Tab and select Microsoft Excel 11.0 Object Library[or what you have in your PC]
Click OK.


Again Go to Add Reference -> COM Tab and select  Microsoft Office 11.0 Object Library and click OK.
Then You will see some additional object in your Project's Reference tree namely Excel, Microsoft.Office.Core

How to Restrict Non-Numeric Key Press in Text Field

Sometimes you may need to do code in such way that the user may not enter dot[.] or any alphabetic character. Only Integer value should be entered into TextField. In such case you may capture the Key pressed by the User and allow only Numeric values.

The following code only takes numeric value without decimal point for textBox1

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}

Thursday, July 28, 2011

How to Change Grid View Cell Back Color

In C#.NET windows application, suppose you want to set color your Data-grid cell based on some criteria or value. The code you need to do is as follows:

int colIndex = 0, rowIndex = 0;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
      colIndex = 9;
      rowIndex = dgvr.Index;
      if (dataGridView1["MatchField", rowIndex].Value != null)
      {
              if (dataGridView1["Match
Field", rowIndex].Value.ToString() == "NotMatch")
              {
                     dataGridView1[colIndex, rowIndex].Style.BackColor = Color.Red;
              }
      }
}


Here in my Data Grid I have marked column 9 which name is "MatchField" and if that column value is "NotMatch" then i made that cell back color into Red.
 

Wednesday, October 13, 2010

How to set icon to .exe file (C#.NET / VB.NET)

If you're using Visual Studio 2005, you can add the .ico/.png file in the C#
project through the Project Designer.

Detail Process:
1. Go to Solution Explorer and Right click the project item and choose Properties.
2. In the Project Designer, switch to the Application tab.
3. Select the option button 'Icon' in the Resources group and click the
button on the right to browse to your .ico file

4. After that save and build the project.
5. Now inside bin\debug u will get the project .exe file with your icon.

Tuesday, October 5, 2010

How to Programmatically Change the Caption of Windows Form using C#

If you would like to change the caption of the windows form during program running then write the following code.

      this.Text = "newForm";   
      
      Here on the right side what you write will display on the Form Caption.

Monday, August 9, 2010

Crystal Report in ASP.NET using C# with DataSet and DataTable

To create crystal report in ASP.NET dataSet and dataTable makes the programming so much easy.  In this article i have tried to show how DataSet ease our work and make the report creation flexible.

1. Add a DataSet to your Project and name it as myDataSet  as follows:
Click Yes. It will create a folder named App_Code in the solution window.
Now add a DataTable to myDataSet. Add columns to your DataTable
Your column name and datatype should be the same as that in your database.
Rename the DataTable name into "InfoTable"(without double quotes).

2. Add a Crystal report to the project and name it as myCrystalReport.
    Choose Using the report wizard.
    Choose the data source from project data which is myDataSet in our case.
Click (>) to move the table into 'Selected Tables' section
Choose the columns to be displayed on the report.

After that clicking finish will show the report which we can change the design at our choice.
Now let's see the code behind which will bind the data to the report.

SqlConnection connection = new SqlConnection("server='SERVER-NAME';uid= 'USER-ID'; "pwd='PASSWORD';database=DATABASE_NAME; Connect Timeout=1000000");
        connection.Open();  

        string selectQry = "YOUR-SQL-QUERY-HERE";        
        DataSet myDS = new DataSet();        
        SqlDataAdapter myDataAdapter = new SqlDataAdapter(selectQry, connection);
        myDataAdapter.Fill(myDS, "InfoTable");
        myReportDocument.Load(@Server.MapPath("myCrystalReport.rpt"));
        myReportDocument.SetDataSource(myDS);
        CrystalReportViewer1.ReportSource = myReportDocument;
        CrystalReportViewer1.DataBind();

Advantage
The main advantage of using DataSet is we can modify the table/Query and get effect from our DataSet. Suppose we may need to add a column in our report. Then we will modify our SQL Query in our program as well as add the new column to the myDataSet DataSet. After that open the Crystal Report and update it by as following way:

Open the Field Explorer -> Right Click on Database Fields -> Click Verify Database. A message will show that the DataSet has changed.
 
Clicking Ok will update the table field. After that we can use that/those field in our Crystal Report. 
Earlier when i use XML file to make report, that time to update the report is bit difficult. If i had a change in my SQL query then i had to build the XML file again, map to that XML into crystalReport and need to design Crystal Report again.
Using Data Set technique its now so much easy.


Keep coding......... and enjoy programming.............