Sometimes, in the application we have a requirement that we need to show all GridView rows in edit mode. This means that all the rows will contain textboxes and the data should be visible in the textboxes. After done with editing we can update and get back to the view mode.
The first task is the create a GridView and add two buttons(one for edit, other for update) like this :-
The first task is the create a GridView and add two buttons(one for edit, other for update) like this :-
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPrice" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("price") %>' />
<asp:TextBox ID="txtPrice" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("price") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblQuantity" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("quantity") %>' />
<asp:TextBox ID="txtQuantity" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("quantity") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="editButton" runat="server" Text="Edit Button" OnClick="editButton_Click" />
<asp:Button ID="updateButton" runat="server" Text="Update Button" OnClick="updateButton_Click" />
As, you can see in the aspx page that both my labels and the textboxes are in the ItemTemplate and their visibility depends on the 'IsInEditMode' property. Now let us see aspx.cs page
public bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindData();
}
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
void bindData()
{
string connectionString = "Server=localhost;Database=master;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT price, quantity FROM demo", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvOrders.DataSource = ds;
gvOrders.DataBind();
}
protected void editButton_Click(object sender, EventArgs e)
{
isEditMode = true;
bindData();
}
protected void updateButton_Click(object sender, EventArgs e)
{
isEditMode = false;
bindData();
lblChatText.Text = "Gridview data updated succesfully";
}
That’s it!!…..Happy Programming...
No comments:
Post a Comment