0

我正在使用此代码从数据库访问数据并将其显示在文本框中,但我columns在第一个文本框中获取整个字符串,如何拆分并显示在相应的文本框中,我Index was outside the bounds of the array.在这行代码中遇到此异常txtOption2.Text = coldata[2];

public EditQuestionMaster(int qid_value)
        {
            InitializeComponent();
            string columns = db.GetEditQuestions(qid_value);
            string[] coldata=columns.Split('$');

                txtQuestion.Text = coldata[0];
                txtOption1.Text = coldata[1];
                txtOption2.Text = coldata[2];
                txtOption3.Text = coldata[3];
                txtOption4.Text = coldata[4];                           

        }

GetEditQuestions(qid_value) 代码

public string GetEditQuestions(int qid)
        {
            string data = "";
            try
            {
                string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
                cmd = new OleDbCommand(sql, acccon);
                rs = cmd.ExecuteReader();
                if (rs.Read())
                {
                    data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
                }
            }
            catch (Exception err)
            {

            }
            return data;
        }

预先感谢您的任何帮助

4

3 回答 3

0

您看到该错误是因为您只有 2 个项目coldata。尝试调试并查看数组的长度coldata以查看它包含多少项。

更改您的代码以使用此拆分:

string[] coldata=columns.Split('~');
于 2013-07-31T14:09:37.227 回答
0

您似乎将字符串拆分,但您使用作为分隔符$构建字符串。~您需要拆分字符串~以获得适当的列数,即

string[] coldata = columns.Split("~")
于 2013-07-31T14:10:08.937 回答
0

Looking at your code sample you just need to change:

string[] coldata=columns.Split('$');

To

string[] coldata=columns.Split('~');

As your columns are delimited by the ~ character.

于 2013-07-31T14:10:15.520 回答