【问题标题】:how to get datagridview current row column value?如何获取datagridview当前行列值?
【发布时间】:2012-05-13 06:40:26
【问题描述】:

我有一个 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

我正在使用此代码动态填充网格视图

    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、contractID、totalpayment 我不知道该怎么做,第二个问题是关于我在存储过程中使用的货币符号是正确的方式还是最好的方式这样做?

【问题讨论】:

    标签: c# sql winforms datagridview


    【解决方案1】:

    正如 volody 所指出的,您可以使用 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 控件变得更加容易,并在运行代码之前确定有关表示层的所有内容(例如将隐藏哪些列、任何额外的计算列、特殊列格式、条件行/column/cell 绘画等)。

    只值我的 0.02 美元。

    【讨论】:

    • dt.Load(dr)中的dr是什么
    • 我刚刚获取了您的代码并将这三行添加到其中。只要确保正确地为您的列设置别名,否则在 UI 层找到它们只会是猜测。
    • DataFormatString。使用 Intellisense 获取您需要设置的确切属性。
    【解决方案2】:

    使用SelectedRows 收藏

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

    【讨论】:

      【解决方案3】:

      要获取值,您将覆盖选择事件。

      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>
      

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

      【讨论】:

      • 这适用于 WinForms DataGridView,而不是 Web.UI GridView。但是,无论如何,逻辑与您的建议非常相似。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多