位置0没有行;

时间:2015-10-08 08:44:36

标签: c# string-concatenation

当我尝试在我的行中获取得分的具体数据时,帮助我不断收到此错误。

我的数据库中有这些数据:

PlayerName    Score
qwe            20
keith          0

我在winform中有这段代码:

using (SqlConnection conn = new SqlConnection("Data Source=Rogue;Initial Catalog=SoftProject;Integrated Security=True"))
{
    conn.Open();
  try
  {
    String str1 = "";
    using (SqlCommand cmd = new SqlCommand("Select PlayerName,Score from PlayerData where PlayerName = @player", conn))
    {
        cmd.Parameters.AddWithValue("@player", txtPlayer.Text);
        DataTable dataTable= new DataTable();
        dataTable.Load(cmd.ExecuteReader());

        if(dataTable.Rows.Count>0)
        {
            // concatenate the two string and get the table score row
            str1 = String.Concat(str1, (dataTable.Rows[0]["Score"].ToString()));
        }
        else
        {
            //Report error
        }
    }

    conn.Close();
  }
  catch()
  {
     MessageBox.Show("No data");
  }
}

在这里的代码中,这会让我的系统出错:

str1 = String.Concat(str1, (dataTable.Rows[0]["Score"].ToString()));

得到' qwe'的名称和分数和' 20'好的 但在第二栏中,基思'和' 0'。 我的代码标记为错误"位置0和#34;;

没有行

string.concat方法()似乎有什么问题?

3 个答案:

答案 0 :(得分:2)

仅使用SqlDatareader就足够了

using (SqlConnection conn = new SqlConnection("Data Source=Rogue;Initial Catalog=SoftProject;Integrated Security=True"))
        {           
            conn.Open();
            try
            {
                String str1 = "";
                using (SqlCommand cmd = new SqlCommand("Select PlayerName,Score from PlayerData where PlayerName = @player", conn))
                {
                    cmd.Parameters.AddWithValue("@player", txtPlayer.Text);
                    SqlDataReader reader = cmd.ExecuteReader();

                    if(reader.Read())
                    {
                        str1 = String.Concat(str1, reader.GetString(reader.GetOrdinal("Score")));
                    }
                    else
                    {

                    }
                }
                conn.Close();
            }
            catch
            {

            }

        }

答案 1 :(得分:1)

使用此代码

using (SqlConnection conn = new SqlConnection("Data Source=Rogue;Initial Catalog=SoftProject;Integrated Security=True"))
{
conn.Open();
try
{
String str1 = "";
using (SqlCommand cmd = new SqlCommand("Select PlayerName,Score from PlayerData where PlayerName = @player", conn))
{
    cmd.Parameters.AddWithValue("@player", txtPlayer.Text);
    DataSet ds= new DataSet();
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    adapter.Fill(ds);

    if(ds.Tables[0].Rows.Count>0)
    {
        // concatenate the two string and get the table score row
        str1 += ds.Tables[0].Rows[0]["Score"].ToString();
    }
    else
    {
        //Report error
    }
    }

    conn.Close();
  }
  catch()
  {
     MessageBox.Show("No data");
  }
}

答案 2 :(得分:0)

试试这个:

if(dt.Rows.Count>0)
{
str1 = String.Concat(str1, (dataTable.Rows[0]["Score"].ToString()));
}