gpt4 book ai didi

c# - 为什么在为行单元格设置文本时得到 'System.ArgumentOutOfRangeException'?

转载 作者:行者123 更新时间:2023-11-30 22:45:03 25 4
gpt4 key购买 nike

使用多个查询,如下面的代码所示,我得到以下异常:

An exception of type 'System.ArgumentOutOfRangeException' - Specified argument was out of the range of valid values

在这一行:

e.Row.Cells[3].Text = count;

可能是什么问题?我尝试了无数不同的东西,但我无法让它工作。我是这方面的新手。

SqlConnection conn;
conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~\\App_Data\\ForumDB.mdf") + ";Integrated Security=True;User Instance=True");
conn.Open();
SqlCommand comm;
comm = new SqlCommand("SELECT COUNT(ThreadId) FROM [Threads] WHERE [TopicId] = @TopicId", conn);
SqlCommand comm2;
comm2 = new SqlCommand("SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = @TopicId", conn);
SqlCommand comm3;
comm3 = new SqlCommand("SELECT PostedBy FROM Threads WHERE PostedDate=(SELECT MAX(PostedDate) FROM [Threads] WHERE [TopicId] = @TopicId", conn);

//FOR COMMAND1 CMD
comm.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
string count = (comm.ExecuteScalar().ToString());
e.Row.Cells[3].Text = count;

//FOR COMMAND2 CMD1
comm2.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm2.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
string count1 = (comm2.ExecuteScalar().ToString());
e.Row.Cells[4].Text = count1;

//for command3 cmd2
comm3.Parameters.Add("@TopicId", System.Data.SqlDbType.Int, 10, "TopicId");
comm3.Parameters["@TopicId"].Value = e.Row.Cells[0].Text;
if (comm3.ExecuteScalar() != null)
{
count2 = (comm3.ExecuteScalar().ToString());
}
conn.close();

最佳答案

这一行的问题:

e.Row.Cells[3].Text = count;

似乎这一行没有 4 个单元格。通过在该行放置一个断点并查看 e.Row.Cells.Count 的值来检查它。它将小于 4。

此外,您可能想要更改执行查询的方式,因为看起来您可以在单个查询中获得所需的所有字段,而不是三个单独的字段:

const string query = 
"SELECT PostedBy, PostedDate, COUNT(ThreadId) AS Count " +
"FROM [Threads] WHERE [TopicId] = @TopicId " +
"ORDER BY PostedDate DESC " +
"LIMIT 1";

var fileToAttach = Server.MapPath("~\\App_Data\\ForumDB.mdf");
var connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + fileToAttach + ";Integrated Security=True;User Instance=True";

var topicId = int.Parse(e.Row.Cells[0].Text);
var postedBy = "";

using (var conn = new SqlConnection(connectionString))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn)
{
cmd.Parameters.AddWithValue("@TopicId", topicId);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// NOTE: I am assuming you have these cells now!
e.Row.Cells[3].Text = reader["Count"].ToString();
e.Row.Cells[4].Text = reader["PostedDate"].ToString();
postedBy = (string)reader["PostedBy"];
}
}
}
}

关于c# - 为什么在为行单元格设置文本时得到 'System.ArgumentOutOfRangeException'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29869196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com