如何从DataTable中的每一行获取特定列。在这个例子中,我想得到前3个新闻,我遇到了Image的问题。这段代码总是给第一行的图像,因为我定义了dr.Rows [0] [“Image”]。如何更改此选项以获得每行的正确图像?
SqlCommand cmd = new SqlCommand("SELECT TOP 3 Title, Content, Date, Autor, Category, Image FROM News", con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
Panel panel = new Panel();
panel.Attributes.Add("class", "post");
HtmlGenericControl header = new HtmlGenericControl("h2");
header.InnerHtml = row["Title"].ToString();
header.Attributes.Add("class", "naslovPosta");
panel.Controls.Add(header);
HtmlGenericControl date = new HtmlGenericControl("p");
date.InnerHtml = ((DateTime)row["Date"]).ToString("dd.MM.yyyy.");
date.Attributes.Add("class", "datumPosta");
panel.Controls.Add(date);
Image img1 = new Image();
img1.ImageUrl = ResolveUrl("~/Images/" + dt.Rows[0]["Image"]);
panel.Controls.Add(img1);
HtmlGenericControl content = new HtmlGenericControl("pre");
content.InnerHtml = row["Content"].ToString();
panel.Controls.Add(content);
pnlNews.Controls.Add(panel);
}
答案 0 :(得分:0)
您已经枚举了所有行,您在row
- 变量中找到了当前行,因此请替换:
img1.ImageUrl = ResolveUrl("~/Images/" + dt.Rows[0]["Image"]);
与
img1.ImageUrl = ResolveUrl("~/Images/" + row["Image"]);
就像你已经做过的那样f.e.在row["Title"].ToString();