ASP.Net C# 使用 Reader 中的第一行
conn = new SqlConnection(connectionString);
comm = new SqlCommand("Products.sl_Cartridges", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@PrinterID", SqlDbType.Int));
comm.Parameters["@PrinterID"].Value = varPrinterID;conn.Open();
reader = comm.ExecuteReader();
Cartridges.DataSource = reader;
Cartridges.DataBind();
reader.Close();
有没有办法在上面添加一些代码来挑选该转发器的第一个数据行的值?它只会让我不必编写一个单独的 SP,这似乎是一种浪费。抱歉,对 .Net 很陌生!
conn = new SqlConnection(connectionString);
comm = new SqlCommand("Products.sl_Cartridges", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@PrinterID", SqlDbType.Int));
comm.Parameters["@PrinterID"].Value = varPrinterID;conn.Open();
reader = comm.ExecuteReader();
Cartridges.DataSource = reader;
Cartridges.DataBind();
reader.Close();
Is there a way to add some code behind to the above to pick out the values of the first data row of this repeater? It would just save me writing a separate SP which seems a waste. Sorry very new to .Net!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果返回的结果集非常小,您可以使用 SqlDataAdapter 转储到 DataTable 并获取第一行。这非常简单,但效率很低,因为如果结果很大,就会浪费一堆不必要的数据流:
Edit: dt.Rows[0] 无效,因为它必须是一个列表。替换为
dt.Rows.Take(1)
(如果您有 LINQ)或new [] { dt.Rows[0] }
。否则,您将需要从读取器的第一行获取所有值,并将它们转储到可以绑定到 Cartridges 控件的对象中:
此外,如果您使用像 DetailsView 这样的控件而不是 Repeater,它将自动仅显示一次一行,您可以将其过滤为一行。
If the result set returned is very small, you can just dump to a DataTable with a SqlDataAdapter and grab the first row. This is very simple but inefficient because it wastes a bunch of unnecessary data flow if the result size is large:
Edit: dt.Rows[0] is not valid because it must be a list. Replace with
dt.Rows.Take(1)
(if you have LINQ) ornew [] { dt.Rows[0] }
.Otherwise, you will need to grab all the values from the first row in the reader and dump them into an object that can be bound to the Cartridges control:
Also, if you use a control like DetailsView instead of Repeater, it will automatically display only one row at a time, and you can filter it to a single row.
这不是一个很好的解决方案,但您可以为转发器的 ItemDataBound 事件添加一个处理程序,并将每个项目(第一个项目除外)的 Visible 属性设置为 false:
markup:
code-behind:
Not a very nice solution, but you could add a handler for the repeater's ItemDataBound event and set the Visible property of each item (except the first one) to false:
markup:
code-behind: