how to get datagridview current row column value?

25,504

Solution 1

As volody pointed out, you can use the SelectedRows property to get everything you need. However, you might not know the indexes of the columns in question (although they're usually generated in the same order as the query, so make sure to alias the columns properly), you can use the column text itself via string access on the cells:

foreach(DataGridViewRow row in DataGridView1.SelectedRows)
{
    // Do something with row.Cells["CustID"].Value;
    // Do something with row.Cells["ContractID"].Value;
    // Do something with row.Cells["TotalPayment"].Value;
}

The other thing I would suggest you do is to leave the formatting up to the DataGridView instead of the SQL query. This is generally best practice when separating your data access/business logic layer from your presentation/UI layer. The way you would do this would be to specify a DataFormatString on the DataTable's DataColumn for the columns in question. In this particular case, you would do this:

...
DataTable dt = new DataTable();
dt.Load(dr);
dt.Columns["TotalPayment"].DataFormatString = "C";
dt.Columns["MonthlyInstallment"].DataFormatString = "C";
dt.Columns["TotalCommission"].DataFormatString = "C";
dataGridView1.DataSource = dt;

The downside to doing everything in code is that you don't get any design-time support, meaning you have to test everything out during run-time (which could be time consuming). That's one of the reasons ORM's are used (such as the VS DataSet Designer, LINQ2SQL designer, EntityFramework, etc), so that you have design-time support of database queries/objects. It makes it even easier to bind these data classes directly to UI controls at design-time and determine everything about the presentation layer before even running the code (such as which columns will be hidden, any additional computed columns, special column formatting, conditional row/column/cell painting, etc).

Just my $0.02 worth.

Solution 2

Use SelectedRows collection

int columnOfcustID = 0; // change this to correct custID column index
int columnOfcontractID = 1; // change this to correct contractID column index
int columnOftotalpayment = 2; // change this to correct totalpayment column index
foreach(DataGridViewRow row in DataGridView1.SelectedRows)
{
    Console.WriteLine(row.Cells[columnOfcustID].Value);
    Console.WriteLine(row.Cells[columnOfcontractID].Value);
    Console.WriteLine(row.Cells[columnOftotalpayment].Value);
}
Share:
25,504
mepk
Author by

mepk

Updated on May 04, 2020

Comments

  • mepk
    mepk about 4 years

    I have a winform which has a gridview that is populating through a stored procedure the stored procedure is

        ALTER PROCEDURE [dbo].[spGetAllCustumer]
    
        AS
        SET NOCOUNT ON 
    SET XACT_ABORT ON  
        BEGIN TRAN
      BEGIN
    SELECT     Customer.CustID, Customer.CustName, Customer.CompanyName, Customer.CompanyRealtion, Contract.ContractID, Contract.ContractDate, 
                      '$'+ CONVERT(varchar,Contract.totalPayment,1), '$'+ CONVERT(varchar,Contract.monthlyInstallment,1), '$'+ CONVERT(varchar,Contract.totalCommission,1), Contract.ContractDuration, Contract.PaymentMode, Contract.Description, 
                      Customer.Disable
    FROM         Customer INNER JOIN
                      Contract ON Customer.CustID = Contract.CustID
    WHERE     (Customer.Disable = 'false')
    
     END
    commit
    

    and I'm populating the gridview dynamically with this code

        con.ConnectionString = "Data Source=MRDEVELOPER;Initial Catalog=Crystal_Accounts;Integrated Security=True";
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandText = "spGetAllCustumer";
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.Clear();
                con.Open();
                SqlDataReader dr = com.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Load(dr);
                dataGridView1.DataSource = dt;
    

    I want to select the custID, contractID, totalpayment of the selectedRow i don't know how can i do it and second question is about the currency sign that i used in the storedprocedure is it right way or what is the best way to do that?

  • SPFiredrake
    SPFiredrake about 12 years
    This is for WinForms DataGridView, not the Web.UI GridView. However, the logic is pretty similar to what you're suggesting anyway.
  • mepk
    mepk about 12 years
    What is dr in dt.Load(dr)
  • SPFiredrake
    SPFiredrake about 12 years
    I just took your code and added those three lines to it. Just be sure to properly alias your columns, otherwise finding them is going to be nothing but guesswork at the UI layer.
  • SPFiredrake
    SPFiredrake about 12 years
    DataFormatString. Use Intellisense to get the exact property that you need to set.