[英]Check value of datatable with C#
I want to check if values of datatable of the same column are equals to "int" or not, so if it's true i want to calculate with content value the sum.我想检查同一列的数据表的值是否等于“int”,所以如果它是真的,我想用内容值计算总和。 This is my code which return always when i click on sum button "pas tous entier".
这是我的代码,当我点击总和按钮“pas tous entier”时,它总是返回。 Thank you in advance!
先感谢您!
private void button7_Click(object sender, EventArgs e)
{
int i = 0, s = 0;
String type ="int";
DataTable dt = new DataTable("Table_insertion");
bool exists = dt.AsEnumerable().Any(row => type == row.Field<String>("Type"));
if (exists== true)
{
for (i = 0; i < dataGridView1.Rows.Count; ++i)
{
s += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);
}
label5.Text = s.ToString();
}
else
{
MessageBox.Show("pas tous entiers");
}
}
The datatable seems unnecessary here.数据表在这里似乎是不必要的。
Maybe the following is enough.也许以下就足够了。
for (i = 0; i < dataGridView1.Rows.Count; ++i)
{
var str = dataGridView1.Rows[i].Cells[2].Value?.ToString();
if( !string.IsNullOrEmpty(str) && Int32.TryParse(str, out var parsed)
{
s += parsed;
}
}
If you want to check the type of the column in a datatable you can check its DataType
.如果要检查数据表中列的类型,可以检查其
DataType
。
foreach (var col in datatable1.Columns)
{
if ( col.DataType == typeof(System.Int16) || col.DataType == typeof(System.Int32)) // Or other types
{
....
Are you just trying to evaluate if the string returned contains only numbers?您是否只是想评估返回的字符串是否仅包含数字? If so, you may want to use a regex match on the data.
如果是这样,您可能希望对数据使用正则表达式匹配。 There is a great example here: Regex for numbers only
这里有一个很好的例子: Regex for numbers only
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.