C# 如何获取datagridview当前行列值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10436631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get datagridview current row column value?
提问by mepk
I have a winform which has a gridview that is populating through a stored procedure the stored procedure is
我有一个 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
and I'm populating the gridview dynamically with this code
我正在使用此代码动态填充 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;
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?
我想选择 selectedRow 的 custID、contractID、totalpayment 我不知道我该怎么做,第二个问题是关于我在存储过程中使用的货币符号是正确的方法还是最好的方法?
采纳答案by SPFiredrake
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:
正如 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;
}
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 DataFormatStringon the DataTable's DataColumn for the columns in question. In this particular case, you would do this:
我建议您做的另一件事是将格式留给 DataGridView 而不是 SQL 查询。这通常是将数据访问/业务逻辑层与表示/UI 层分开时的最佳实践。执行此操作的方法是DataFormatString在 DataTable 的 DataColumn 上为相关列指定 a 。在这种特殊情况下,您将执行以下操作:
...
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).
在代码中做所有事情的缺点是你没有得到任何设计时支持,这意味着你必须在运行时测试所有内容(这可能很耗时)。这是使用 ORM 的原因之一(例如 VS 数据集设计器、LINQ2SQL 设计器、EntityFramework 等),以便您在设计时支持数据库查询/对象。它可以更轻松地在设计时将这些数据类直接绑定到 UI 控件,并在运行代码之前确定有关表示层的所有内容(例如将隐藏哪些列、任何额外的计算列、特殊列格式、条件行/列/单元格绘画等)。
Just my $0.02 worth.
只是我的 0.02 美元。
回答by volody
Use SelectedRowscollection
使用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);
}
回答by Brandon
To get the values you would override the select event.
要获取值,您将覆盖 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);
}
You could also create the columns in your code...
您还可以在代码中创建列...
Using a TemplateField you could evaluate your dollar amounts to a label or another control using the following syntax
使用 TemplateField,您可以使用以下语法将美元金额评估为标签或其他控件
<asp:TemplateField HeaderText="Total Payment">
<itemTemplate>
<asp:label id="lblTotalPayment" Text='<%# Eval("TotalPayment","{0:C}") %>' runat="server" />
</itemTemplate>
</asp:TemplateField>
However to go that route you would have to setup all the fields and not just one.
但是,要走这条路线,您必须设置所有字段,而不仅仅是一个。

