"输入字符串的格式不正确."

Ahs*_*ain 11 .net c# visual-studio-2010 winforms

我正在开发一个项目,我在其中有一个表单,通过该表单我可以在列表视图中编辑可用的问题.每当我从列表视图中选择一行并单击"修改"按钮时,列表视图上方的文本框会加载问题及其选项.这意味着当我在列表视图中选择一行并单击"修改"按钮时,问题会将其自身加载到文本框中.我在那里编辑问题并单击"保存"以保存更改,但我无法访问文本框中的数据.它说{"Input string was not in a correct format."}.

我的表单frmFormWizard's'编辑'按钮的代码如下:

frmFormWizard.cs代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;

namespace SurveyBuilder
{
    public partial class frmFormWizard : Form
    {
        int intPanelNumber = 1;
        Boolean blnCancel = false;
        //int intFlag = 1;

        public frmFormWizard()
        {
            InitializeComponent();
        }

        ...

        private void btnEditTwoOrMoreOptions_Click(object sender, EventArgs e)
        {
            int QuestionID;           
            string sql;

            QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
            {
                SqlConnection cn = new SqlConnection();
                SqlCommand rs = new SqlCommand();
                SqlDataReader sdr = null;
                clsConnection clsCon = new clsConnection();

                clsCon.fnc_ConnectToDB(ref cn);

                sql = "";
                sql += "SELECT * FROM SurveyQuestionLog WHERE SurveyQuestionLog.QuestionLogID = "+ QuestionID +"";
                //sql += "SELECT * FROM SurveyQuestionLog";

                rs.Connection = cn;
                rs.CommandText = sql;
                sdr = rs.ExecuteReader();

                while (sdr.Read())
                {
                    txtTwoOrMoreQuestions.Text = (string)sdr["Question"];
                    txtOption1.Text = (string)sdr["Choice1"];
                    ...
                }

                sdr.Close();
                rs = null;
                cn.Close();
            }
        }
Run Code Online (Sandbox Code Playgroud)

每当我尝试编译它所说的代码时"{"Input string was not in a correct format."}",此错误显示在以下行:

 QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
Run Code Online (Sandbox Code Playgroud)

请让我知道我做错了什么.

Sum*_*shk 5

它看起来像文本中包含一些空格.使用

lvTwoOrMoreOptions.SelectedItems [0] .Text.ToString().修剪()

并转换为int32.

希望这段代码能解决你

来自评论

如果您的ListView处于报告模式(即它看起来像一个网格),那么您将需要SubItems属性.lvTwoOrMoreOptions.SelectedItems获取列表视图中的每个项目 - SubItems为您提供列.因此lvTwoOrMoreOptions.SelectedItems[0].SubItems[0]是第一列值,

  • @Ayesha Noor:如果你的ListView处于报告模式(即它看起来像一个网格),那么你将需要SubItems属性.lvTwoOrMoreOptions.SelectedItems获取列表视图中的每个项目 - SubItems为您提供列.所以lvTwoOrMoreOptions.SelectedItems [0] .SubItems [0]是第一个列值,试试这个.如果您的问题得到解决,请将我的答案标记为解决 (2认同)