sondmk header
C# Programming

C# : DataGridview Set : Width, text-center

Post by Goborijung at 2020-10-10 13:41:12 | ID: 842

dgMain.Columns[0].Width = 30; //Set columns width
dgMain.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //Set text center, MiddleCenter

C# : Get RowsCount and ColumnsCount in Excel Files

Post by Goborijung at 2020-09-23 16:11:13 | ID: 821

Ref: http: //csharpexamples.com/c-read-data-excel-file/

// CREATE EXCEL OBJECTS.
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range excelRange;

int iRow,
iCol = 2;

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(sFile); // WORKBOOK TO OPEN THE EXCEL FILE.
xlWorkSheet = xlWorkBook.Worksheets[1]; // NAME OF THE SHEET.

excelRange = xlWorkSheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;

// getRowCount
MessageBox.Show("RowCount : " + rowCount.ToString("#,0##"));
// getColCount
MessageBox.Show("ColCount : " + colCount.ToString("#,0##"));

C# : Get Sql to DataTable And Read Data in DataTable

Post by Goborijung at 2020-12-04 09:20:36 | ID: 903

//>> Pull dbData to dataTable

var dt = new DataTable(); using(var da = new SqlDataAdapter("Select * From SMPLRequestFabricParts Where OIDSMPLFB = " + FBID + " ", mainConn)) { da.Fill(dt); }

//>> Read Data in Datatable

foreach(DataRow row in dt.Rows) { string OIDGParts = row["OIDGParts"].ToString(); Console.WriteLine(OIDGParts); }

C# : Import Excel | Read an Excel file in Windows Forms Application using C#

Post by Goborijung at 2020-09-23 15:04:37 | ID: 819

Ref: https://www.encodedna.com/windows-forms/read-an-excel-file-in-windows-forms-application-using-csharp-vbdotnet.htm

// Add “Microsoft.Office.Interop.Excel” Reference


// mport the Namespace in your Project (C#)
using Excel = Microsoft.Office.Interop.Excel;

// ตัวอย่าง Code

public Form1()
{
  InitializeComponent();
}

// OPEN FILE DIALOG AND SELECT AN EXCEL FILE.
private void cmdSelect_Click(object sender, EventArgs e)
{
  string sFileName;

  OpenFileDialog1.Title = "Excel File to Edit";
  OpenFileDialog1.FileName = "";
  OpenFileDialog1.Filter = "Excel File|*.xlsx;*.xls";

  if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
  {
    sFileName = OpenFileDialog1.FileName;

    if (sFileName.Trim() != "")
    {
      readExcel(sFileName);
    }
  }
}

// GET DATA FROM EXCEL AND POPULATE COMB0 BOX.
private void readExcel(string sFile) {
  // CREATE EXCEL OBJECTS.
  Excel.Application xlApp = new Excel.Application();
  Excel.Workbook xlWorkBook;
  Excel.Worksheet xlWorkSheet;

  int iRow, iCol = 2;
  
  xlApp = new Excel.Application();
  xlWorkBook = xlApp.Workbooks.Open(sFile); // WORKBOOK TO OPEN THE EXCEL FILE.
  xlWorkSheet = xlWorkBook.Worksheets["Sheet1"]; // NAME OF THE SHEET.

  for (iRow = 2; iRow <= xlWorkSheet.Rows.Count; iRow++) // START FROM THE SECOND ROW.
  {
    if (xlWorkSheet.Cells[iRow, 1].value == null) {
      break; // BREAK LOOP.
    }
    else { // POPULATE COMBO BOX.
      cmbEmp.Items.Add(xlWorkSheet.Cells[iRow, 1].value);
    }
  }

  xlWorkBook.Close();
  xlApp.Quit();
}

C# : Import Excel by Reference Class Office :: Recommend

Post by Goborijung at 2020-09-23 15:17:45 | ID: 820

/* Add Refference to Use */

using Excel = Microsoft.Office.Interop.Excel;

// Create Function ReadExcelFiles

private void readExcel(string sFile) { // CREATE EXCEL OBJECTS. Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; int iRow , iCol = 2; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(sFile); // WORKBOOK TO OPEN THE EXCEL FILE. xlWorkSheet = xlWorkBook.Worksheets[1]; // NAME OF THE SHEET. // getRowCount // MessageBox.Show("RowCount : "+xlWorkSheet.Rows.Count.ToString("#,0##")); // getColCount // MessageBox.Show("ColCount : "+xlWorkSheet.Columns.Count.ToString("#,0##")); dataGridView1.Rows.Clear(); dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy; dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White; dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.Single; dataGridView1.GridColor = Color.Black; dataGridView1.ColumnCount = 4; dataGridView1.Columns[0].HeaderText = ""; //chkBox Columns dataGridView1.Columns[1].HeaderText = "No"; dataGridView1.Columns[2].HeaderText = "Customer"; dataGridView1.Columns[3].HeaderText = "Season"; for (iRow = 2; iRow <= xlWorkSheet.Rows.Count; iRow++) // START FROM THE SECOND ROW. { int n = dataGridView1.Rows.Add(); if (xlWorkSheet.Cells[iRow, 1].value == null) { break; } else { //cmbEmp.Items.Add(xlWorkSheet.Cells[iRow, 1].value); //Cell[0] is CheckBox dataGridView1.Rows[n].Cells[1].Value = xlWorkSheet.Cells[iRow, 1].value; dataGridView1.Rows[n].Cells[2].Value = xlWorkSheet.Cells[iRow, 2].value; dataGridView1.Rows[n].Cells[3].Value = xlWorkSheet.Cells[iRow, 3].value; } } xlWorkBook.Close(); xlApp.Quit(); }

// Action Event Click

private void btnGetExcelRowCount_Click(object sender, EventArgs e) { openFileDialog1.Title = "Excel File to Edit"; openFileDialog1.FileName = ""; openFileDialog1.Filter = "Excel File|*.xlsx;*.xls"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { string sFileName = openFileDialog1.FileName; //MessageBox.Show("Filename : "+sFileName); if (sFileName.Trim() != "") { readExcel(sFileName); } } }

C# : Import Excel Files to DataGridView

Post by Goborijung at 2020-09-14 15:59:10 | ID: 800

private void btnChooseFile_Click(object sender, EventArgs e)
{
  try
  {
    OpenFileDialog openfile1 = new OpenFileDialog();
    if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
      this.textBox1.Text = openfile1.FileName;
    }
  }
  catch { }
}

private void btnExcelLoad_Click(object sender, EventArgs e)
{
  try
  {
    string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
    OleDbConnection conn = new OleDbConnection(pathconn);
    OleDbDataAdapter da = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
    DataTable dt = new DataTable();
    da.Fill(dt);

    dataGridView1.DataSource = dt;
    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {
      dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString();
    }
  }
  catch { }
}

C# : Import Excel to Gridview

Post by Goborijung at 2020-09-23 14:58:28 | ID: 818

private void btnImportExcel_Click(object sender, EventArgs e)
{
  // Connection Files | Replace ! to BlackSlash
  string part = "D:!!Office!!Excel!!";
  string filename = "PrintBarcode - importOrder.xlsx";
  string sheetname = "TB SKUOrder";
  string connExcel = "Provider = Microsoft.jet.OLEDB.4.0; Data source="+part+filename+";"+ "Extended Properties=!"Excel 8.0;HDR= yes;!";";

  // Connection conn
  OleDbConnection conn    = new OleDbConnection(connExcel);
  conn.Open();
  OleDbCommand cmd        = new OleDbCommand("select * from ["+sheetname+"$]", conn);
  OleDbDataReader dr      = cmd.ExecuteReader();

  // Add Columns Header
  dataGridView1.Rows.Clear();
  dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
  dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
  dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.Single;
  dataGridView1.GridColor = Color.Black;

  dataGridView1.ColumnCount = 4;
  dataGridView1.Columns[1].HeaderText = "";
  dataGridView1.Columns[1].HeaderText = "No";
  dataGridView1.Columns[2].HeaderText = "Customer";
  dataGridView1.Columns[3].HeaderText = "Season";

  int i = 1;
  while (dr.Read())
  {
    // Create n row getDate From dr[] Array
    int n = dataGridView1.Rows.Add();

    // if Columns In Excel Index is null or = ""
    if (Convert.ToString(dr[0]) == "")
    {
      break;                    
    }
    else
    {
      //Cell[0] is CheckBox                = True/false;
      dataGridView1.Rows[n].Cells[1].Value = dr[0];
      dataGridView1.Rows[n].Cells[2].Value = dr[1];
      dataGridView1.Rows[n].Cells[3].Value = dr[2];
    }

    i++;
  }

  conn.Close();

  // ShowStatus Bar
  tssl_RowCount.Text = "Total Row : "+(i-1).ToString()+" Records";
}

C# : OpenFileDialog

Post by Goborijung at 2020-09-23 13:14:06 | ID: 817

private void btnChooseFile_Click(object sender, EventArgs e)
{
  try
  {
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
      this.textBox1.Text = ofd.FileName;
    }
  }
  catch { }
}

C# : Print Document Page

Post by Goborijung at 2020-09-19 16:27:38 | ID: 810

Use Object :
printDialog
printDocument

// Print
private void button2_Click(object sender, EventArgs e)
{
  printDialog1.Document = printDocument1;
  if(printDialog1.ShowDialog() == DialogResult.OK)
  {
    printDocument1.Print();
  }
}

// Document PrintPage
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
  e.Graphics.DrawString("Hello C#",new Font("Arial",12,FontStyle.Bold), Brushes.Black, new PointF(100,30));
}

C# : Process Examples

Post by Goborijung at 2020-09-10 09:46:38 | ID: 761

Ref : https://www.dotnetperls.com/process
C# program that opens directory

using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Use Process.Start here.
        Process.Start("C:\");
    }
}

// --------------------------------------------

C# program that opens text file

using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Open the file "example.txt".
        // ... It must be in the same directory as the .exe file.
        Process.Start("example.txt");
    }
}

// ---------------------------------------------

C# program that launches web browser

using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Call method.
        SearchDuckDuckGo("cat pictures");
    }

    static void SearchDuckDuckGo(string term)
    {
        // Search DuckDuckGo for this term.
        Process.Start("https://www.duckduckgo.com/?q=" + term);
    }
}

// ------------------------

C# program that starts WINWORD.EXE

using System.Diagnostics;

class Program
{
    static void Main()
    {
        // ... Open specified Word file.
        OpenMicrosoftWord(@"C:UsersSamDocumentsGears.docx");
    }

    /// <summary>
    /// Open specified word document.
    /// </summary>
    static void OpenMicrosoftWord(string file)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "WINWORD.EXE";
        startInfo.Arguments = file;
        Process.Start(startInfo);
    }
}

// ----------------------------

C# program that runs EXE

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    static void LaunchCommandLineApp()
    {
        const string ex1 = "C:\";
        const string ex2 = "C:Dir";

        // Part 1: use ProcessStartInfo class.
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;

        // Part 2: set arguments.
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Part 3: start with the info we specified.
            // ... Call WaitForExit.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
            // Log error.
        }
    }
}

// --------------------------

C# program that uses GetProcesses method

using System;
using System.Diagnostics;

class Program
{
    static void Main()
    {
        // Show all processes on the local computer.
        Process[] processes = Process.GetProcesses();
        // Display count.
        Console.WriteLine("Count: {0}", processes.Length);
        // Loop over processes.
        foreach (Process process in processes)
        {
            Console.WriteLine(process.Id);
        }
    }
}

Output

Count: 70
388
5312
1564
972
2152
936
3132....

// ---------------------

C# program that uses GetProcessesByName

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
        while (true)
        {
            // Omit the exe part.
            Process[] chromes = Process.GetProcessesByName("chrome");
            Console.WriteLine("{0} chrome processes", chromes.Length);
            Thread.Sleep(5000);
        }
    }
}

Output

0 chrome processes
3 chrome processes
4 chrome processes
5 chrome processes
5 chrome processes
5 chrome processes

// -----------------------------------

C# program that redirects standard output

using System;
using System.Diagnostics;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Set up the process with the ProcessStartInfo class.
        //
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"C:7za.exe"; // Specify exe name.
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        //
        // Start the process.
        //
        using (Process process = Process.Start(start))
        {
            //
            // Read in all the text from the process with the StreamReader.
            //
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }
}

Output

7-Zip (A)  4.60 beta  Copyright (c) 1999-2008 Igor Pavlov  2008-08-19

Usage: 7za <command> [<switches>...] <archive_name> [<file_names>...]
       [<@listfiles...>]

// --------------------------

C# program that uses Process Kill method

using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
        // Start notepad.
        Process process = Process.Start("notepad.exe");
        // Wait one second.
        Thread.Sleep(1000);
        // End notepad.
        process.Kill();
    }
}       

<<<12345678910...>>>

Framework

Library


เครื่องมือพัฒนาเว็บ



การออกแบบและพัฒนาเว็บไซต์


Download SourceCode



copyAllright © 2016 soundmk.com