从sql数据库中解析列,并绑定到网格中的特定列
本文关键字:网格 绑定 数据库 sql | 更新日期: 2023-09-27 18:01:21
我在SQL表中有1列名为Colors (Colors nchar(10) NOT NULL
)的字符串。颜色可以是红色、蓝色、绿色、黄色或橙色。在同一个表中,我有一个名为names (Names nchar(20) NOT NULL
)的列,其中保存了孩子的名字。我有一个网格在我的ASP。NET应用程序,每一种颜色(红、蓝、绿、黄或橙)有五列,另一列用于名称。我的网格中的每一行代表一个孩子,对于每个孩子,孩子最喜欢的颜色应该用布尔值标记。有简单的方法吗?
不寻找超级特定的代码—只是通过每个子名称的for循环的框架。谢谢!
假设通过"标记为布尔值",您希望在网格中使用复选框控件来显示每个颜色列的真/假值,您可以尝试这样做:
一个GridView控件示例(为了简洁,我没有包括数据绑定代码):
<asp:GridView ID="childGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" />
<asp:TemplateField HeaderText="Red">
<ItemTemplate>
<asp:CheckBox ID="Red" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Green">
<ItemTemplate>
<asp:CheckBox ID="Green" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Yellow">
<ItemTemplate>
<asp:CheckBox ID="Yellow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Orange">
<ItemTemplate>
<asp:CheckBox ID="Orange" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
在代码隐藏类中:
void ctlGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView item = (DataRowView)e.Row.DataItem;
//get value of Color from the bound data
string color = item["Color"].ToString();
//make sure that the casing (i.e., lower, upper or proper) of each checkbox ID matches what's in the DB
((CheckBox)e.Row.FindControl(color)).Checked = true;
}
}
重要提示:在这个例子中,我使用了一个简单的约定,即假设GridView中每个CheckBox控件的ID与"Children"表的Color列中的值匹配(区分大小写的匹配)。显然,您可以通过使用特定的大小写(例如lower、upper或proper)来修改ID命名方案,并修改我提供的代码隐藏代码以解释特定的大小写。
一种方法是将颜色'物化'到结果集中的布尔列中。警告:如果你的颜色列表变大,这可能不能很好地缩放-但这个概念是常见的。
给定CREATE TABLE dbo.Children ( ChildID INT Identity,
Name NVARCHAR(20)
, Color NCHAR(10)
)
和一些示例数据:
INSERT INTO dbo.Children (Name, Color) Values ('Ted', 'Red')
INSERT INTO dbo.Children (Name, Color) Values ('Alice', 'Green')
模式看起来像这样:
SELECT c.ChildID
, c.Name
, CAST( CASE WHEN c.Color = 'Red' THEN 1 ELSE 0 END as BIT) as LovesRed
, CAST( CASE WHEN c.Color = 'Green' THEN 1 ELSE 0 END as BIT) as LovesGreen
-- ... one for each color
FROM dbo.Children c
我还意识到我把你的列名改成了单数(color而不是colors)…因为这是一个根深蒂固的标准。
你可以绑定LovesGreen
和LovesRed
(等)到你的网格在一个非常直接的方式
你可以这样做:
protected void dgvSearch_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
string myVal = e.Row.Cells[1].Text;
if (myVal == "Red")
{
e.Row.Cells[1].Text = "True";
}
}
}
您必须遍历每行上的单元格,但是上面的示例向您展示了如何选择单元格并设置文本。