Display text in DataGridView when there are no rows


Display text in DataGridView when there are no rows

   
if (dt.Rows.Count > 0)
                {
                    grid1.DataSource = dt;
                    grid1.DataBind();
                }
                else
                {
                    dt.Rows.Add(dt.NewRow());
                    grid1.DataSource = dt;
                    grid1.DataBind();
                    int totalcolums = grid1.Rows[0].Cells.Count;
                    grid1.Rows[0].Cells.Clear();
                    grid1.Rows[0].Cells.Add(new TableCell());
                    grid1.Rows[0].Cells[0].ColumnSpan = totalcolums;
                    grid1.Rows[0].Cells[0].Text = "No Data Found";
                }


Reading Excel files from C# OR How to read data from excel file using c#


Reading Excel files from C# OR How to read data from excel file using c#

The following C# source code using Microsoft Excel 12.0 Object Library for reading an Excel file.

 namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            Excel.Range range ;

            string str;
            int rCnt = 0;
            int cCnt = 0;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open("sourcecodemaster.xls", 0, true, 5, "", "", true, 

Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;

            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
                    MessageBox.Show(str);
                }
            }

            xlWorkBook.Close(true, null, null);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 

    }
}
  

Converting a string to byte-array without using an encoding (byte-by-byte)


Converting a string to byte-array without using an encoding (byte-by-byte)


 static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}  
 static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}

How do you convert Byte Array to Hexadecimal String, and vice versa


How do you convert Byte Array to Hexadecimal String, and vice versa


 public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}  

OR
public static string ByteArrayToString(byte[] ba)
{
  string hex = BitConverter.ToString(ba);
  return hex.Replace("-","");
}  

OR
  public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

Create Excel (.XLS and .XLSX) file from C#


Create Excel (.XLS and .XLSX) file from C#

You can use a library called ExcelLibrary.
It's very simple, small and easy to use. you can use DataSets and DataTables to easily work with Excel data.Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:

   
//Create the dataset and table
DataSet ds = new DataSet("NewDataSet");
DataTable dt = new DataTable("NewDataTable");

//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

//Open a DB connection (example OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();

//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();

adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();

//Add the table to the data set
ds.Tables.Add(dt);

//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("sourcecodemaster.xls", ds);



Microsoft Excel 12.0
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; 

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                MessageBox.Show("Excel is not properly installed!!");
                return;
            }


            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet.Cells[1, 1] = "Sheet 1 content";

            xlWorkBook.SaveAs("C:\\sourcecodemaster.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            MessageBox.Show("Excel file created , you can find the file d:\\sourcecodemaster.xls");
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

    }
}


Connection String

connection string in c#

You can connect your C# application to data in a SQL Server database using the .NET Framework Data Provider for SQL Server. The first step in a C# application is to create an instance of the Server object and to establish its connection to an instance of Microsoft SQL Server.
The SqlConnection Object is Handling the part of physical communication between the C# application and the SQL Server Database . An instance of the SqlConnection class in C# is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement.

connetionString="Data Source=ServerName; Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

If you have a named instance of SQL Server, you'll need to add that as well.

 "Server=localhost\sqlexpress"

Connect via an IP address

connetionString="Data Source=IP_ADDRESS,PORT; Network Library=DBMSSOCN;Initial Catalog=DatabaseName; User ID=UserName;Password=Password"

Trusted Connection from a CE device ( 1433 is the default port SQL )

 connetionString="Data Source=ServerName; Initial Catalog=DatabaseName;Integrated Security=SSPI; User ID=myDomain\UserName;Password=Password;

Connecting to SQL Server using windows authentication

 "Server= localhost; Database= employeedetails; Integrated Security=SSPI;"


c# calculator program source code


c# calculator program source code

Today I am going to show you how to build a Calculator. It is recommended that you get the visual studio environment. if you don't understand the code don't be afraid to ask questions by leaving a comment below.



using System;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        float num1, ans;
        int count;
 
        private void btnC_Click_1(object sender, EventArgs e)
        {
            textBox1.Clear();
            count = 0; 
        }
 
        private void btnCE_Click(object sender, EventArgs e)
        {
            
            if (num1==0 && textBox1.TextLength>0)
            { 
                num1 = 0; textBox1.Clear();  
            }
            else if (num1 > 0 && textBox1.TextLength > 0)
            { 
                textBox1.Clear();
            }
        
        }
 
        private void btnback_Click(object sender, EventArgs e)
        {
           
            int lenght = textBox1.TextLength-1;
            string text = textBox1.Text;  
            textBox1.Clear();
            for (int i = 0; i < lenght; i++)
                textBox1.Text = textBox1.Text + text[i]; 
        
        }
 
        private void btnminus_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "")
            {
                num1 = float.Parse(textBox1.Text);
                textBox1.Clear();
                textBox1.Focus();
                count = 1;
            }
        }
 
        private void btnone_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 1;
        }
 
        private void bttntwo_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 2;
        }
 
        private void btnthree_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 3;
        }
 
        private void btnplus_Click(object sender, EventArgs e)
        {
            num1 = float.Parse(textBox1.Text);
            textBox1.Clear();
            textBox1.Focus();
            count = 2;
        }
 
        private void btnfour_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 4;
        }
 
        private void btnfive_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 5;
        }
 
        private void btnsix_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 6;
        }
 
        private void btnmultiply_Click(object sender, EventArgs e)
        {
            num1 = float.Parse(textBox1.Text);
            textBox1.Clear();
            textBox1.Focus();
            count = 3;
        }
 
        private void btnseven_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 7;
        }
 
        private void btneight_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 8;
        }
 
        private void btnnine_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 9;
        }
 
        private void btndivide_Click(object sender, EventArgs e)
        {
            num1 = float.Parse(textBox1.Text);
            textBox1.Clear();
            textBox1.Focus();
            count = 4; 
        }
 
        private void btnzero_Click(object sender, EventArgs e)
        {
            textBox1.Text = textBox1.Text + 0;
        }
 
        private void btnperiod_Click(object sender, EventArgs e)
        {
            int c = textBox1.TextLength;
            int flag = 0;
            string text = textBox1.Text;
            for (int i = 0; i < c; i++)
            { 
                if (text[i].ToString() == ".") 
                { 
                    flag = 1; break; 
                } 
                else 
                { 
                    flag = 0; 
                } 
            }
            if (flag == 0)
            { 
                textBox1.Text = textBox1.Text + "."; 
            }
        }
 
        private void btnequal_Click(object sender, EventArgs e)
        {
            compute(count);
        }
 
        public void compute(int count)
        {
            switch (count)
            {
                case 1:
                    ans = num1 - float.Parse(textBox1.Text);
                    textBox1.Text = ans.ToString();
                    break;
                case 2:
                    ans = num1 + float.Parse(textBox1.Text);
                    textBox1.Text = ans.ToString();
                    break;
                case 3:
                    ans = num1 * float.Parse(textBox1.Text);
                    textBox1.Text = ans.ToString();
                    break;
                case 4:
                    ans = num1 / float.Parse(textBox1.Text);
                    textBox1.Text = ans.ToString();
                    break;
                default:
                    break;
            }
        }
       
     }
}