我有数据库表,其中我有两列名称picid和pic1..in我的pic1列我有三个数据..现在想要使用sqldatareader重新检索数据我得到列数据的顶部..how获取该列的所有数据并将其用于进一步的目的..
我的代码
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
grpIDreader.Read();
string path = grpIDreader["pic1"].ToString();
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path);
image2.Attributes["src"] = String.Format("{1}", path);
image3.Attributes["src"] = String.Format("{2}", path);
}
我想获取保存在数据库的pic1列中的路径。 我收到此错误“System.FormatException:索引(从零开始)必须大于或等于零且小于参数列表的大小。” 我也尝试了同样的错误
protected void Page_Load(object sender, EventArgs e)
{
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From pictable", objsqlconn);
SqlDataReader grpIDreader = cmd.ExecuteReader();
string[] path={"","",""};
int i = 0;
while(grpIDreader.Read())
{
path[i++] = grpIDreader["pic1"].ToString();
}
//slide.Attributes["style"] = String.Format("background-image:url('{0}')", path);
image1.Attributes["src"] = String.Format("{0}", path[0]);
image2.Attributes["src"] = String.Format("{1}", path[1]);
image3.Attributes["src"] = String.Format("{2}", path[2]);
}
答案 0 :(得分:0)
您收到字符串格式错误,而不是数据库错误:
image1.Attributes["src"] = String.Format("{0}", path); //This works, as 0 indicates the first argument you are passing in
image2.Attributes["src"] = String.Format("{1}", path); //This won't work, as you are asking for the second argument, which doesn't exist
答案 1 :(得分:0)
使用以下内容获取每一行
using (SqlDataReader grpIDreader = cmd.ExecuteReader())
{
while (grpIDreader.Read()) //.Read() advances to the next row and returns false if there are no more
{
string path = grpIDreader["pic1"].ToString();
//other stuff here
}
}
也
而不是
image1.Attributes["src"] = String.Format("{0}", path[0]);
这样做
image1.Attributes["src"] = path[0];