如何增加计数值 [英] How do I increment count value

查看:86
本文介绍了如何增加计数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void LinkButton1_Click(object sender, EventArgs e)
   {
       count = 0;

        string s = Session["r"].ToString();
           string s2 = Session["r2"].ToString();
           string s3 = Session["r3"].ToString();
           string s4 = Session["r4"].ToString();
       string t="Select * from Test_paper Where Paper_id='8'";
       DataTable dt3 = new DataTable();
       dt3 = c2.bindgrid(t);
       if (dt3.Rows[0][9].ToString() == s)
       {
           count = count + 1;
       }
       else
       {
           count = count + 0;
       }
      if (dt3.Rows[0][15].ToString() == s2)
       {
           count = count + 1;
       }
       else
       {
           count = count + 0;
       }


       if (dt3.Rows[0][20].ToString() == s3)
       {
           count = count + 1;
       }
       else
       {
           count = count + 0;
       }

      if (dt3.Rows[0][25].ToString() == s4)
       {
           count = count + 1;
       }
       else
       {
           count = count + 0;
       }


       Label2.Text =count.ToString();

   }

推荐答案

我不确定我的建议是否以任何方式解决了您的问题,但检查是否这些有帮助。首先,如果你想让一个计数器在任何一个匹配上递增,那么为什么不呢?

I am not sure whether my suggestions any way solves your problem or not but check if these helps. First of all, if you want a single counter to be incremented on any of the match then why not this-
if ((dt3.Rows[0][9].ToString()) == s || (dt3.Rows[0][15].ToString() == s2) || (dt3.Rows[0][20].ToString() == s3) || (dt3.Rows[0][25].ToString() == s4))
{
    count ++; //equivalent to count=count+1;
}



这段代码与你的4组if..else语句的结果相同。



其次,通过索引从数据表列访问值不是一个好习惯。如果您通过列名来访问它们会更具可读性且不易出错,例如


This piece of code yields same result as that of your 4 sets of if..else statements.

Secondly, it is not a good practice to access value from data table columns by index. It would be more readable and less error-prone if you access them by their column names like

//dt3.Rows[0][20].ToString()  --bad idea
dt3.Rows[0]["columnName"].ToString();





此外,您还没有检查数据表是否包含任何行,这可能会导致异常。确保在所有这些操作之前进行了检查。



Also, you haven't checked if the data table contains any rows or not, which may lead to exception. Make sure that you have put check before all these operations.

if(dt3.Rows.Count>0)
{
 // write rest of the logic here
}



这些只是建议更好的代码的建议,可能无法解决您的问题,但可以帮助您比以前更轻松地识别您的问题。


These are just suggestion for building better code and may not solve your problem but can help you identify your problem easier than earlier.


这篇关于如何增加计数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆