Wednesday, 17 October 2012

How to get file path in C#

How could i get the right path for a file in C#?

Use openfiledialog,for following code
 
private void button1_Click(object sender,Eventargs e)
{
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
textbox1.Text=Path.GetFullPath(openFileDialog1.FileName);
}
}
 
addionally add the namespace System.IO;

C# to Call SQL Server Stored Procedure with Data Reader



Hey.. In this post, i will share about How to Call SQL Server's Stored Procedure from C# Console Application. You can do this in Windows Form, Web Form, ASP.NET MVC, etc. The concept is same but for simplicity, i will use Console Application for this example.

First, you must create the Stored Procedure inside your database. In this example, i will create a stored procedure that accepts numeric score for its input parameter, and return letter score for its output. Here is the syntax :



Second, you must create a client application that will create a connection with the database. It will also send an input as a parameter for the Stored Procedure and return the letter value. I encapsulate it as a method in this example. Here is the code :


Here is the explanation. It creates a connection with SqlConnection object. It gives a connection string as a parameter for its constructor. It also defines SqlCommand object for its command container. SqlDataReader object is a reader for the database that will read a result for the Stored Procedure. It's often called Connected Mechanism. After defining some important variable,  it executes the Stored Procedure, gets the result and returns the result as a return data for this method.

After define the method to communicate with the database, we can give a simple program for user to input their score and get his/her letter score. Here is the code..


Execute the program, and you will get the result like below : 



Insert your numeric score, and you will get your letter score.


Tuesday, 9 October 2012

DataGridView Select row programatically

How can I programatically make a row in a DataGridView selected?

"Rows" is a property of the DataGridView that returns all the rows as a collection.  For a particular Row, you can set the .Selected property to True (or False) to select (or unselect) that Row.
For example,

dataGridView1.Rows(index).Selected = True

here,
 index you have to  mention any value like 1,2,3

DataGridView to insert combobox into selective cells

This is an example of a column:
Column 1, Row 1 = textboxcell
Column 1, Row 2 = textboxcell
Column 1, Row 3 = comboboxcell
Column 1, Row 4 = textboxcell
How can I do that?
You can do it like this(VB.net):
DataGridView1.Columns.Add("Column 1", "Column 1")
DataGridView1.RowCount = 3
DataGridView1.Rows(0).Cells(0) = New DataGridViewTextBoxCell
DataGridView1.Rows(1).Cells(0) = New DataGridViewTextBoxCell
DataGridView1.Rows(2).Cells(0) = New DataGridViewComboBoxCell
DataGridView1.Rows(3).Cells(0) = New DataGridViewCheckBoxCell
C#:
dataGridView1.Columns.Add("Column 1", "Column 1");
dataGridView1.RowCount = 3;
dataGridView1.Rows(0).Cells(0) = new DataGridViewTextBoxCell();
dataGridView1.Rows(1).Cells(0) = new DataGridViewTextBoxCell();
dataGridView1.Rows(2).Cells(0) = new DataGridViewComboBoxCell();
dataGridView1.Rows(3).Cells(0) = new DataGridViewCheckBoxCell();

DataGridView - Make multiple cells editable at the same time

I put the button Column into DGV control. Additionally, when the button is pressed, all the cells are enables (read to edit) and the text into row bolds. You can disable the editing on two ways:
- or clicking another row (the new row will be enabled, and the previous one disabled)
- or clicking the button again (so for the 2nd time)
I did the code, and it was tested -works perfect - I hope this is what you have wanted!
In my text code the dgv only has 3 columns (its an example). So you only have to modify it to your needs, and here we go:

namespace EditCells
{
  public partial class Form1 : Form
  {
    List<Customer> list;
    public Form1()
    {
      InitializeComponent();
      InitializingBS();
      CreatingDGV();
      //create a click event for the dgv`s buttons:
      dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
    }

    private void CreatingDGV()
    {
      //setting datasurce and stuff:
      dataGridView1.AutoGenerateColumns = false;
      dataGridView1.AllowUserToAddRows = false;
      dataGridView1.RowHeadersVisible = false;
      dataGridView1.DataSource = list;

      //creating columns:
      dataGridView1.Columns.Add("col1", "Id");
      dataGridView1.Columns.Add("col2", "Customer name");
      DataGridViewButtonColumn columnButton = CreatingButtonColumn();
      dataGridView1.Columns.Add(columnButton);
      
      dataGridView1.Columns[0].DataPropertyName = "id";
      dataGridView1.Columns[1].DataPropertyName = "name";
      
      //disabling columns:
      dataGridView1.Columns[0].ReadOnly = true;
      dataGridView1.Columns[1].ReadOnly = true;      
    }
    private DataGridViewButtonColumn CreatingButtonColumn()
    {
      DataGridViewButtonColumn column = new DataGridViewButtonColumn();
      {
        column.HeaderText = "";
        column.Name = "GetRowId";
        column.Text = "Enable row";
        column.UseColumnTextForButtonValue = true;
        column.ReadOnly = true;
      }
      return column;
    }

    private void InitializingBS()
    {
      list = new List<Customer>();
      Customer customer1 = new Customer(1, "Mitja Bonca");
      Customer customer2 = new Customer(2, "Sara McRae");
      Customer customer3 = new Customer(3, "John Dollan");
      Customer[] array = new Customer[3] { customer1, customer2, customer3 };
      for (int i = 0; i < array.Length; i++)
        list.Add(array[i]);
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (e.ColumnIndex != dataGridView1.Columns["GetRowId"].Index) return;
      int row = e.RowIndex;
      for (int i = 0; i < dataGridView1.Rows.Count; i++)
      {
        foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
        {
          if (i == row)
          {
            if (cell.ReadOnly == false)
            {
              //if the button is pressed for 2nd time, the row will be disabled and text to regular:
              cell.Style.Font = new Font(cell.InheritedStyle.Font, FontStyle.Regular);
              cell.ReadOnly = true;
            }
            else
            {
              //the enabled rows will get a bold text:
              cell.Style.Font = new Font(cell.InheritedStyle.Font, FontStyle.Bold);
              cell.ReadOnly = false;
            }
          }
          else
          {            
            //all the other rows will be disables and fort changes back to rwgular:
            cell.Style.Font = new Font(cell.InheritedStyle.Font, FontStyle.Regular);
            cell.ReadOnly = true;
          }
        }
      }
    }
  }

  public class Customer
  {
    public int id { get; set; }
    public string name { get; set; }

    public Customer(int _id, string _name)
    {
      id = _id;
      name = _name;
    }
  }
}

Datagridview create rows progrmatically, readonly rows, read only cells

How to create rows progrmatically in the datagridview?

How to make certain rows as read-only?

How to make certain cells as read-only?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        const int numberOfColumns = 10;
        const int numberOfRows = 5;
        public Form1()
        {
            InitializeComponent();
            for (int columnCount = 0; columnCount < numberOfColumns; 
                   columnCount++)
            {
                DataGridViewColumn NewColumn =
                   new DataGridViewColumn();
                DataGridViewCell cell = new DataGridViewTextBoxCell();
                cell.Style.BackColor = Color.Wheat;
                NewColumn.CellTemplate = cell;
                dataGridView1.Columns.Add(NewColumn);
            }
            int RowNumber;
            DataGridViewRow NewRow;
            for(int rowCount = 0; rowCount < numberOfRows; rowCount++)
            {
               RowNumber = dataGridView1.Rows.Add();
               NewRow = dataGridView1.Rows[RowNumber];
               for (int columnCount = 0; columnCount < numberOfColumns; 
                  columnCount++)
               {
                   NewRow.Cells[columnCount].Value = columnCount.ToString();
               }
               NewRow.ReadOnly = true;
            }
 
        }
    }
}

 

C# Datagridview rows count

This post to help to know to find the ow many rows are in datagridview ..

textBox1.Text = dataGridView1.Rows.Count.ToString();

Same time in your datagridview have "add new row" is enable then you have to use like that,

textBox1.Text = (dataGridView1.Rows.Count - 1).ToString()

Monday, 8 October 2012

How to add new line in messagebox

How to Create Multi Line Text ?
VB.NET :


in vb.net, "&vbnewline&" is used to add a new line in the messagebox.show();
e.g.
 messagebox.show("this is first line" & vbnewline & "this is second line");

C#.NET :


In C# (like most C derived languages), escape characters are used to denote special characters such as return and tab, and + is used in place of & for string concatenation.
To make your code work under C# you’ve got two options... the first is to simply replace the vbNewLine with the return escape character \n ala:

            MessageBox.Show("this is first line" + "\n" + "this is second line");

The other method, and more correct is to replace it instead with Environment.NewLine which theoretically could change depending on the system you are using (however unlikely).

            MessageBox.Show("this is first line" + "Environment.NewLine" + "this is second line");

Also I'd like to add; If you would like to take advantage of ``Environment.NewLine'' as Brendan suggested you could do something like this to make it more legible IMO::

Console.WriteLine( "This is Line1{0} This is Line2{0}", Environment.NewLine );
[Output]
This is Line1
 This is Line2
// Or...
MessageBox.Show( string.Format( "This is Line1{0} This is Line2{0}", Environment.NewLine ) );
[Output]
This is Line1
 This is Line2
// Or...
string msg = string.Format( "This is Line1{0} This is Line2{0}", Environment.NewLine );
MessageBox.Show( msg );
[Output]
This is Line1

MessageBox with Yes or No Dialogresult

How To Create Yes or No Dialogresult in C# ?

Way - 1
DialogResult dialogResult = MessageBox.Show("Are You Sure you want to Process ?", "Warrning", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
    //do something
}
else if (dialogResult == DialogResult.No)
{
    //do something else
}
Way - 2
DialogResult dr = MessageBox.Show("Are You Sure you want to Process ?", 

                      "Warrning", MessageBoxButtons.YesNo);

switch(dr){

   case DialogResult.Yes: break;

   case DialogResult.No: break;

}
Out Put like 




Sunday, 7 October 2012

C# DateTimePicker Getting Date only

How To Change Date Format in Datetimepicker ?

First drag the datetimepicker ..






Goto the datetimepicker Properties..

And do this Steps.. one by one







 Finlay We Get it

C# comboBox Add Static Data

How To Add Static Data in ComboBox ?
Way -1 :
 First drag combobox in your windows form..






And goto combobox Properties

Select the Items and click the button.. then one window will come..
 
 

After Enter your Data here...

 
Finaly Click Ok.. and Press F5 or Run