问题
I've put together a GridView table in ASP.net that allows users to approve a series of records. As part of this approval process, I'd like to provide an empty column for the user to provide comments where necessary. The only records showing up will be records that haven't been approved yet, thus, no comments will need to be loaded. Once they are approved, users will not be able to view these records again.
How do I go about adding this empty column to my GridView? Again, there's no data to load into this column. Once approved, the records in the SQL Server table will be updated with a timestamp and comments.
Most of what I was able to find on here so far has been related to adding empty rows, but not columns. I'm completely new to ASP.net, so any help would be greatly appreciated.
Current Column Code:
asp:TemplateField HeaderText="Comment" ItemStyle-Width="500px" ItemStyle-Wrap="true" SortExpression="Comment" /
回答1:
Just a simple solution I've quickly put together. It uses the OnRowCommand event of the GridView.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="TextBox">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Text='<%# Eval("textfield") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UpdateButton">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Update" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//cast the sender back to a gridview
GridView gv = sender as GridView;
//cast the commandsource back to a button
Button btn = e.CommandSource as Button;
//cast the namingcontainer of the button back to a gridviewrow
GridViewRow row = btn.NamingContainer as GridViewRow;
//find the correct textbox using findcontrol and the index obtained from the row
TextBox tb = gv.Rows[row.DataItemIndex].FindControl("TextBox1") as TextBox;
//show result
Label1.Text = tb.Text;
}
UPDATE
Or if you want to update all the records at once by pressing a button.
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
TextBox tb = row.FindControl("TextBox1") as TextBox;
Label1.Text += tb.Text + "<br>";
}
}
来源:https://stackoverflow.com/questions/44660032/how-to-add-an-empty-unbound-comment-column-to-a-gridview