简体   繁体   中英

accessing data from database and displaying it in textbox

I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code 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) Code

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;
        }

thank you in advance for any help

You are seeing that error because you only have 2 items in coldata . Try debugging and view the length of the coldata array to see how many items it contains.

Change your code to use this split instead:

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

You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns ie

string[] coldata = columns.Split("~")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM