C# 如何获取datagridview当前的行-列值?

C# 如何获取datagridview当前的行-列值?,c#,sql,winforms,datagridview,C#,Sql,Winforms,Datagridview,我有一个winform,它有一个gridview,它通过一个存储过程填充存储过程 ALTER PROCEDURE [dbo].[spGetAllCustumer] AS SET NOCOUNT ON SET XACT_ABORT ON BEGIN TRAN BEGIN SELECT Customer.CustID, Customer.CustName, Customer.CompanyName, Customer.CompanyRealtion

我有一个winform,它有一个gridview,它通过一个存储过程填充存储过程

    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
我用这段代码动态填充gridview

    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;
我想选择所选账户的custID、CONSTRACTID、totalpayment。我不知道该怎么做,第二个问题是关于我在Stored流程中使用的货币符号。这是正确的方法还是最好的方法?

使用托收

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);
}

要获取值,您将覆盖select事件

void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{

   GridViewRow row = GridView1.Rows[e.NewSelectedIndex];

   //get value from cells
   String var = row.Cells[1].Text; 

   //do something with the value or pass the values to a function here
   DoSomething(var);
}
您还可以在代码中创建列

使用TemplateField,您可以使用以下语法将美元金额计算为标签或其他控件

<asp:TemplateField HeaderText="Total Payment">
<itemTemplate>
    <asp:label id="lblTotalPayment" Text='<%# Eval("TotalPayment","{0:C}") %>' runat="server" />
</itemTemplate>
</asp:TemplateField>


但是,要走这条路线,您必须设置所有字段,而不仅仅是一个字段

正如沃洛迪所指出的,您可以使用SelectedRows属性获取所需的一切。但是,您可能不知道相关列的索引(尽管它们通常以与查询相同的顺序生成,因此请确保正确地为列别名),您可以通过对单元格的字符串访问来使用列文本本身:

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;
}
我建议您做的另一件事是将格式设置留给DataGridView,而不是SQL查询。在将数据访问/业务逻辑层与表示/UI层分离时,这通常是最佳做法。这样做的方法是在DataTable的DataColumn上为相关列指定一个
DataFormatString
。在这种情况下,您可以执行以下操作:

...
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;
在代码中执行所有操作的缺点是,您没有获得任何设计时支持,这意味着您必须在运行时测试所有内容(这可能很耗时)。这就是使用ORM的原因之一(例如VS数据集设计器、LINQ2SQL设计器、EntityFramework等),以便在设计时支持数据库查询/对象。这使得在设计时将这些数据类直接绑定到UI控件变得更加容易,甚至在运行代码之前就可以确定表示层的所有内容(例如哪些列将被隐藏、任何其他计算列、特殊列格式、条件行/列/单元格绘制等)


只有我的0.02美元价值。

这是针对WinForms DataGridView的,而不是Web.UI GridView。然而,逻辑与您的建议非常相似。dt.Load(dr)中的dr是什么?我刚刚获取了您的代码并将这三行添加到其中。只需确保正确地为列添加别名,否则在UI层查找它们只会是猜测。
DataFormatString
。使用Intellisense获取需要设置的确切属性。