C# 将默认行添加到ASP.NET GridView的顶部
我有一个GridView,它是从具有特定值的SqlDataSource填充的 如何将默认行添加到myGridView的顶部 我希望默认行中有文本“All”C# 将默认行添加到ASP.NET GridView的顶部,c#,asp.net,gridview,C#,Asp.net,Gridview,我有一个GridView,它是从具有特定值的SqlDataSource填充的 如何将默认行添加到myGridView的顶部 我希望默认行中有文本“All” <asp:GridView ID="gvPoints" runat="server" DataSourceID="SqlDataSource_userPoints" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="id_po
<asp:GridView ID="gvPoints"
runat="server"
DataSourceID="SqlDataSource_userPoints"
AllowPaging="True"
AutoGenerateColumns="False"
DataKeyNames="id_point,title"
BorderWidth="0px"
Width="100%"
GridLines="None">
<Columns>
<asp:ButtonField
CommandName="selectedPoint"
DataTextField="title"
ButtonType="Link" />
</Columns>
<RowStyle HorizontalAlign="Left"></RowStyle>
</asp:GridView>
<asp:SqlDataSource
ID="SqlDataSource_userPoints"
runat="server"
ConnectionString='<%$ ConnectionStrings:TipTourConnectionString %>'
SelectCommand ="SELECT
id_point,
title,
body
FROM tt_point
WHERE id_user = @id_user">
<SelectParameters>
<asp:QueryStringParameter
QueryStringField="id_user"
DefaultValue="0"
Name="id_user">
</asp:QueryStringParameter>
</SelectParameters>
</asp:SqlDataSource>
我认为在这种情况下,最简单的方法是将其与SQL语句一起添加
这假定id_点是一个数字字段。如果没有,请删除convert函数
SELECT 'All' AS id_point, 'All' AS title, 'All' AS body
UNION
SELECT CONVERT(varchar, id_point), title, body FROM tt_point WHERE id_user = @id_user
替换这个
<asp:ButtonField CommandName="selectedPoint" DataTextField="title" ButtonType="Link" />
在页面加载时调用此方法,如下所示
strcon = "data source=.\\SQLEXPRESS;database=testDB;trusted_Connection=yes";
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT id_point,title,body FROM tt_point WHERE id_user = @id_user", connection);
string userid = "0";
command.Parameters.AddWithValue("@id_user", userid);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
DataRow dr = dt.NewRow();
dr["id_point"] = "All";
dr["title"] = "All";
dr["body"] = "All";
dt.Rows.InsertAt(dr, 0);
DataRow dr1 = dt.NewRow();
dr1["id_point"] = "All";
dr1["title"] = "All";
dr1["body"] = "All";
dt.Rows.InsertAt(dr1, 1);
gvPoints.DataSource = dt;
gvPoints.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}
这里的strcon
数据库名是testDB
替换为您的数据库名
将其从gridview中删除不管怎样,有人能解释一下如何使用标记或在后面的代码中实现这一点吗?这可能是最简单的方法,再次感谢@Clint b这里没有网格的row.Add()方法。因此,在代码隐藏中执行此操作的最佳方法是将数据表绑定到网格。在进行绑定之前,您需要将该行添加到DataTable中。但是,由于您使用DataSourceID属性将数据绑定到网格,这是不可能的。这使得它看起来更像标题,如果我有两个默认值add@blitzeus2个默认值,你是指行吗?@blitzeus我修改了我的答案,请检查
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridData();
}
}