为什么这个for循环不起作用 [英] why this for loop is not working

查看:109
本文介绍了为什么这个for循环不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void CBSalesOrderNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string conSTR = "Data Source=" +
                (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) +
                "\\freedom.sdf;Persist Security Info=False";
            
            try
            {
                SqlCeConnection conn = new SqlCeConnection(conSTR);
                conn.Open();
                string code = "SELECT Shipmentno,Custname,Itemno,Bundleno,Validatedby FROM Items WHERE Salesorder ='" + CBSalesOrderNo.Text + "'";
                SqlCeDataAdapter da = new SqlCeDataAdapter(code, conn);
                SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
                DataSet dset = new DataSet();
                da.Fill(dset);
                if (CBSalesOrderNo.SelectedIndex > -1)
                {
                   
                    txtShipmentNo.Text = dset.Tables[0].Rows[0 ["Shipmentno"].ToString();
                    txtcustName.Text = dset.Tables[0].Rows[0]["Custname"].ToString();
                    txtitem.Text = dset.Tables[0].Rows[0]["Itemno"].ToString();
                    List<bundledetails> bundleList = new List<bundledetails>();
                   
                    for (int i = 0; i &lt; bundleList.Count; i++)
                    {
                        string data = dset.Tables[i].Rows[i]["Bundleno"].ToString() + dset.Tables[i].Rows[i]["Validatedby"].ToString();
                        bundleList.Add(new BundleDetails { BundleNo = data });
                        dataGrid1.DataSource = bundleList;
                    }
                  
                    
                 
                 
                    
                   // string data = dset.Tables[0].Rows[0]["Bundleno"].ToString() + dset.Tables[0].Rows[0]["Validatedby"].ToString();
                    //if (!string.IsNullOrEmpty(data))
                    //{
                    //    bundleList.Add(new BundleDetails { BundleNo = data });
                    //    dataGrid1.DataSource = bundleList;
                    //    lblcount.Text = dataGrid1.VisibleRowCount.ToString();
                    //}
                }
            }
            catch (SystemException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        public class BundleDetails
        {
            public string BundleNo { get; set; }
            public string Validatedby { get; set; }

        }




更新:来自评论




Update: from comments

using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlServerCe;

namespace Freedom_2._0
{
    public partial class Dispatch : Form
    {

        SqlCeConnection con = new SqlCeConnection();
        SqlCeCommand Cmd = new SqlCeCommand();
        string ConStr = null;
        DataSet ds = new DataSet();
        public Dispatch()
        {
            InitializeComponent();
        }
        private void Dispatch_Load(object sender, EventArgs e)
        {

        }
        private void SycItems()
        {
            string Path = null;
            string Line = null;
            string FileName = null;
            StreamReader Reader = default(StreamReader);
            Path = "\\My Documents";
            try
            {
                ConStr = "Data Source =" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\freedom.sdf";
                con.ConnectionString = ConStr;
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                Cmd.Connection = con;

                try
                {
                    if (File.Exists(Path + "\\Items.csv"))
                    {
                        FileName = "Items.txt";
                        Cmd.CommandText = "Delete from Items";
                        Cmd.ExecuteNonQuery();
                        FileInfo ItemsFile = new FileInfo(Path + "\\Items.csv");
                        Reader = ItemsFile.OpenText();


                        do
                        {

                            Line = Reader.ReadLine();
                            if (!(string.IsNullOrEmpty(Line)))
                            {
                                string[] values = Line.Split(',');
                                //Edit column name
                                Cmd.CommandText = "Insert Into Items (No,Salesorder,Shipmentno,Custname,Itemno,Bundleno,Validatedby,Rollno,Qty,Transid,Validatedby,RecordID)values('" + values[0] + "','" + values[1] + "','" + values[2] + "','" + values[3] + "','" + values[4] + "','" + values[5] + "','" + values[6] + "','" + values[7] + "','" + values[8] + "','" + values[9] + "','" + values[10].Replace('\'', ' ') + "')"; 

                              Cmd.ExecuteNonQuery();
                            }
                        } while (!(Line == null));
                        Reader.Close();

                        if (File.Exists(Path + "\\Items.csv"))
                        {
                            File.Delete(Path + "\\Items.csv");
                        }
                        MessageBox.Show("CSV Imported Successfuly", "Import CSV");
                    }
                    else
                    {
                        MessageBox.Show("Items File is not found", "Import CSV");
                        Application.Exit();
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Error in Items File", "Import CSV");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error", "Import CSV");
            }

        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            SycItems();
        }

        private void label1_ParentChanged(object sender, EventArgs e)
        {

        }

        private void CBSalesOrderNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string conSTR = "Data Source=" +
                (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) +
                "\\freedom.sdf;Persist Security Info=False";
            
            try
            {
                SqlCeConnection conn = new SqlCeConnection(conSTR);
                conn.Open();
                string code = "SELECT Shipmentno,Custname,Itemno,Bundleno,Validatedby FROM Items WHERE Salesorder ='" + CBSalesOrderNo.Text + "'";
                SqlCeDataAdapter da = new SqlCeDataAdapter(code, conn);
                SqlCeCommandBuilder cmd = new SqlCeCommandBuilder(da);
                DataSet dset = new DataSet();
                da.Fill(dset);
                if (CBSalesOrderNo.SelectedIndex &gt; -1)
                {
                   
                    txtShipmentNo.Text = dset.Tables[0].Rows[0]["Shipmentno"].ToString();
                    txtcustName.Text = dset.Tables[0].Rows[0]["Custname"].ToString();
                    txtitem.Text = dset.Tables[0].Rows[0]["Itemno"].ToString();




                    List<bundledetails> bundleList = new List<bundledetails>();

                    for (int i = 0; i &lt; dset.Tables[i].Rows.Count; i++)
                    {
                        string data = dset.Tables[0].Rows[i]["Bundleno"].ToString() + dset.Tables[0].Rows[i]["Validatedby"].ToString();
                        bundleList.Add(new BundleDetails { BundleNo = data });
                        dataGrid1.DataSource = bundleList;
                    }


                    //for (int i = 0; i &lt; bundleList.Count; i++)
                    //{
                    //    string data = dset.Tables[0].Rows[0]["Bundleno"].ToString() + dset.Tables[0].Rows[0]["Validatedby"].ToString();
                    //    if (!string.IsNullOrEmpty(data))
                    //    {
                    //        bundleList.Add(new BundleDetails { BundleNo = data });
                    //        dataGrid1.DataSource = bundleList;
                    //        lblcount.Text = dataGrid1.VisibleRowCount.ToString();
                    //    }
                    //}





                //string data = dset.Tables[0].Rows[0]["Bundleno"].ToString() + dset.Tables[0].Rows[0]["Validatedby"].ToString();
                //if (!string.IsNullOrEmpty(data))
                //{
                //    bundleList.Add(new BundleDetails { BundleNo = data });
                //    dataGrid1.DataSource = bundleList;
                //    lblcount.Text = dataGrid1.VisibleRowCount.ToString();
                //}
                }
            }
            catch (SystemException se)
            {
                MessageBox.Show(se.Message);
            }
        }
        public class BundleDetails
        {
            public string BundleNo { get; set; }
            public string Validatedby { get; set; }

        }
        private void btnpopulate_Click(object sender, EventArgs e)
        {
          
            string conSTR = "Data Source=" +(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) +
                "\\freedom.sdf;Persist Security Info=False";
            
                try
                {
                    CBSalesOrderNo.Items.Clear();
                    txtShipmentNo.Text = "";
                    txtcustName.Text = "";
                    txtitem.Text = "";
                    SqlCeConnection cn = new SqlCeConnection(conSTR);
                    cn.Open();
                    SqlCeCommand cm = new SqlCeCommand("SELECT DISTINCT Salesorder From Items", cn);
                    SqlCeDataAdapter ds = new SqlCeDataAdapter(cm);
                    DataTable dt = new DataTable();
                    dt.Load(cm.ExecuteReader());
                    DataRow dr = null;  
                    for (int i = 0; i &lt; dt.Rows.Count; i++ )
                    {
                        dr = dt.Rows[i];
                        CBSalesOrderNo.Items.Add(dr[0].ToString());
                      
                    }
                  
                    cn.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
        }

        private void lblcount_ParentChanged(object sender, EventArgs e)
        {
          
        }

    }
}

推荐答案

这都没有道理-在下面查看我的注释

None of this makes any sense - look at my annotations below

//new empty list - the count is zero because it's new
List<bundledetails> bundleList = new List<bundledetails>();

//The for will go from x=0 to x<0 i.e. it will not loop
for (int i = 0; i < bundleList.Count; i++)
{
  //even if it did loop, it wouldn't work

  //Ok on first loop 'i' would be 0 so dset.Tables[0].  second loop would be dset.Tables[1]. This will break because there is no table[1]
  string data = dset.Tables[i]
      //you are also iterating the row?
     .Rows[i]
     ["Bundleno"].ToString() + dset.Tables[i].Rows[i]["Validatedby"].ToString();
  //ah - now you add to the list.
  bundleList.Add(new BundleDetails { BundleNo = data });
  dataGrid1.DataSource = bundleList;
}



试试这个:



try this:

//new empty list - the count is zero because it's new
List<bundledetails> bundleList = new List<bundledetails>();

//The for will go from x=0 to x<0 i.e. it will not loop
//for (int i = 0; i < bundleList.Count; i++)
//you want to loop the rows in the first table and only because your query returns only 1 table
for(int i = 0; i < dset.Tables[0].Rows.Count; i++
{
  //we have the row count so we iterate the rows (ONLY)
  string data = dset.Tables[0].Rows[i]["Bundleno"].ToString() + dset.Tables[0].Rows[i]["Validatedby"].ToString();
  //ah - now you add to the list.
  bundleList.Add(new BundleDetails { BundleNo = data });
  dataGrid1.DataSource = bundleList;
}



您需要了解我是什么以及数据集包含的内容.

编辑
还-这很糟糕:



You need to understand what i is and what your dataset contains.

EDIT
also - this is very bad:

string code = "SELECT Shipmentno,Custname,Itemno,Bundleno,Validatedby FROM Items WHERE Salesorder ='" + CBSalesOrderNo.Text + "'";



如果我在文本框中输入'';drop table items;--怎么办?

请改用参数

更新:
不确定您了解我的意思是sql注入和使用参数


您的代码看起来很破损.我猜你没有写太多.

看这个:



what if I put '';drop table items;-- in the textbox?

Use parameters instead

UPDATE:
Not sure you understood what I meant by sql injection and using parameters


Your code looks broken. I''m guessing that you didn''t write much of it.

Look at this:

//you only need a foreach.  It'll make your code easier to read / maintain
foreach (DataRow row in dset.Tables[i].Rows)
{
    //Extract the values you need.  It helps readability
    string bundleNo = row["Bundleno"].ToString();
    string validatedBy = row["Validatedby"].ToString();

    //Also, you can return here and add some validation like "if(string.IsNullOrEmpty(bundleNo) continue;"

    //It's fine using the class instantiation to build your object, but try to break things up if you can when your just learning.  It'll help you in the long run
    BundleDetails data = new BundleDetails
                             {
                                 BundleNo = bundleNo , 
                                 ValidatedBy = validatedBy  
                             }

    bundleList.Add(data);

    //don't bind every time you change the list.  This is the most likely cause of your current issue.
    //dataGrid1.DataSource = bundleList;
}
//bind after the loop
dataGrid1.DataSource = bundleList;


这篇关于为什么这个for循环不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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