这是我得到的错误:
索引(从零开始)必须大于或等于零且小于参数列表的大小
这是代码:
<%@ Page Language="C#"%>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<!DOCTYPE html>
<script runat="server">
public void Page_Load()
{
string a, c;
a = Request.Form["username"];
string connstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("SQL/Site_Database.accdb");
string sqlstring = string.Format("select * from iUsers_Table where (iusername='{0}')", a);
OleDbDataAdapter da = new OleDbDataAdapter(sqlstring, connstring);
DataSet ds = new DataSet();
da.Fill(ds);
c = Request.Form["mail"];
string connstring1 = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("SQL/Site_Database.accdb");
string sqlstring1 = string.Format("select * from iUsers_Table where (imail='{0}')", c);
OleDbDataAdapter da1 = new OleDbDataAdapter(sqlstring1, connstring1);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
if ((ds.Tables[0].Rows.Count == 0) || (ds1.Tables[0].Rows.Count == 0))
{
string b, d, e, f, g, h;
b = Request.Form["password"];
d = Request.Form["gender"];
e = Request.Form["age"];
f = Request.Form["prob"];
g = Request.Form["prob_val"];
h = Request.Form["fitness"];
sqlstring = string.Format("insert into iUsers_Table (iusername,ipassword,imail,igender,iage,iproblem,iproblem_value,ifitness) values('{0}','{1}','{2}','{3}',{4},'{5}',{6},'{7}')", a, b, c, d, e, f, g, h);
OleDbConnection conn = new OleDbConnection(connstring);
OleDbCommand cmd = new OleDbCommand(sqlstring, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Session["connect_status"] = "connected";
Response.Redirect("My_Plan.aspx");
}
else
{
if ((ds.Tables[0].Rows.Count) > 0)
{
Session["subscribed"] = "exist";
if ((ds1.Tables[0].Rows.Count) > 0)
{
Session["mail"] = "exist";
Response.Redirect("index.aspx");
}
Response.Redirect("index.aspx");
}
}
}
</script>
我创建了一个注册表单,此代码用于将数据插入数据库,并检查现有的相等邮件和用户名值。
有人知道为什么会这样吗?
谢谢!
string sqlstring1 = string.Format("select * from iUsers_Table where (imail='{2}')", c);
{2}不存在,因为字符串中只有一个参数。格式()。请注意,我用谷歌搜索了它,这让我来到了这里(提示提示)。
所以把它改成这样: string sqlstring1 = string.Format("select * from iUsers_Table where (imail='{0}')", c);
然后重试。
正如其他人回答的那样,问题在于您的字符串。格式。但我还想指出,在 C# 6 中添加了内插字符串,这将允许您更改
string sqlstring1 = string.Format("select * from iUsers_Table where (imail='{0}')", c);
自
string sqlstring1 = $"select * from iUsers_Table where (imail='{c}')"
这是一种更干净、更易读的字符串格式格式方法,应该有助于避免将来容易犯错误。
编辑:看到这没有解决您的异常,请确保ds.Tables.Length
大于 0,如果您有ds.Tables[0]
,如果ds.Tables
为空,则会引发异常。
我还注意到你错过了一些引号
sqlstring = string.Format("insert into iUsers_Table (iusername,ipassword,imail,igender,iage,iproblem,iproblem_value,ifitness) values('{0}','{1}','{2}','{3}',{4},'{5}',{6},'{7}')", a, b, c, d, e, f, g, h);
大约{6}
,尽管我不确定这会导致您获得的异常。告诉我们异常发生的位置将有很大帮助。
鉴于您尚未确定发生错误的行,我将假设问题出在这一行代码上,因为它是错误的:
string sqlstring1 = string.Format("select * from iUsers_Table where (imail='{2}')", c);
{2}应该是一个{0},因为它是一个从零开始的索引,你只告诉字符串。期望一个参数的格式。
解决了。这是另一页上的问题。
谢谢大家的评论。 :)