我的问题是如何将值插入到 gridviews 行中。基本上我已经创建了一个 gridview,我在其中绑定(bind)了页脚并且我想在页脚中插入值。我创建了一个“文本框”、“下拉列表”和“复选框'。我想要当我插入值并按“插入”按钮然后值显示在 gridview 中,然后我再次插入值并按下按钮然后在 gridview 中显示插入的值。这是我的 gridview 图像
我也想编辑和删除行。这是我的代码: aspx代码
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="104px" ShowFooter="True" Width="463px"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:TemplateField HeaderText="Column Name">
<FooterTemplate>
<asp:TextBox ID="name" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data Type">
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Allow Null">
<FooterTemplate>
<asp:CheckBox ID="allow_null" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Primary Key">
<FooterTemplate>
<asp:CheckBox ID="primary" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
这是我的 aspx.cs 代码:
protected void Button1_Click(object sender, EventArgs e)
{
string name = TextBox1.Text;
string type = DropDownList1.Text;
string allow=Null.Text;
string primary = Primary.Text;
name = ((TextBox)GridView1.FooterRow.FindControl("TextBox2")).Text;
type = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
allow = ((CheckBox)GridView1.FooterRow.FindControl("allow_null")).Text;
primary = ((CheckBox)GridView1.FooterRow.FindControl("primary")).Text;
}
请您参考如下方法:
要以这种方式使用 GridView,在页脚中输入字段并在 GridView 外部插入一个插入按钮,您需要进行手动插入。
我不知道您如何使用 EF 模型执行插入,因为我目前没有使用它。我想您可能会说“旧”方法是使用 SqlConnection 和 SqlCommand 的实例。您可以在 Button Click 事件中使用与此类似的代码:
// This is VB. C# is similar, you will have to convert where needed
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.CommandType = // Typically Text or StoredProcedure as needed
command.Parameters.AddWithValue("@parameter_name1", some_value_1)
command.Parameters.AddWithValue("@parameter_name2", some_value_2)
.
.
.
command.ExecuteNonQuery()
End Using
End Using
queryString 是你的 sql INSERT 语句或存储过程
command.Parameters 是 INSERT 语句或存储过程中可替换参数的集合。
附录
Gridview 是一种数据绑定(bind)控件,因此通常当您使用 gridview 时,它会绑定(bind)到一些支持数据源。如果您不使用数据库,那么您使用的是其他构造。
例如,如果您使用的是 DataTable,您可以使用行和列方法将新的行和列添加到 DataTable,然后将 DataTable 重新绑定(bind)到 Gridview。您不会将行和列直接添加到 GridView。
