Issue in Update FormView asp.net. - c#

I have sent value through querystring to this Page. After that I am Unable to get Edit Mode on modechanging event. When I click Edit button, simply it postbacks and nothing happens. If Clicked edit second time it gives Error :
(Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.)
Please tell me where I am wrong.
Source Code -
<asp:FormView ID="formview1" runat="server" AllowPaging="true" Caption="FireBrigade" DataKeyNames="FireBrigadeID" OnModeChanging="formview1_ModeChanging"
OnPageIndexChanging="formview1_PageIndexChanging">
<ItemTemplate>
FireBrigade ID :<asp:Label ID="lblFID" runat="server" Text='<%# Eval("FireBrigadeID") %>'></asp:Label><br />
Name :<asp:Label ID="Label3" runat="server" Text='<%# Eval("FBName") %>'></asp:Label><br />
LatLong:<asp:Label ID="Label1" runat="server" Text='<%# Eval("LatLng") %>'></asp:Label><br />
Address: <asp:Label ID="Label2" runat="server" Text='<%# Eval("Address") %>'></asp:Label><br />
Contact: <asp:Label ID="Label4" runat="server" Text='<%# Eval("ContactNumber") %>'></asp:Label><br />
<asp:LinkButton ID="EditButton" Text="Edit" CommandName="Edit" RunAt="server"/>
</ItemTemplate>
<EditItemTemplate>
FireBrigade ID :<asp:TextBox ID="txtFID" runat="server" Text='<%# Bind("FireBrigadeID") %>'></asp:TextBox><br />
Name :<asp:TextBox ID="txtname" runat="server" Text='<%# Bind("FBName") %>'></asp:TextBox>
LatLong:<asp:TextBox ID="txtlatlong" runat="server" Text='<%# Bind("LatLng") %>'></asp:TextBox><br />
Address: <asp:DropDownList ID="ddlAddress" runat="server" OnDataBound="ddlAddress_DataBound" AppendDataBoundItems="true">
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
</asp:DropDownList> <br />
Contact: <asp:TextBox ID="txtcontact" runat="server" Text='<%# Bind("ContactNumber") %>'></asp:TextBox><br />
<asp:LinkButton ID="UpdateButton"
Text="Update"
CommandName="Update"
runat="server" />
<asp:LinkButton ID="CancelUpdateButton"
Text="Cancel"
CommandName="Cancel"
runat="server" />
</EditItemTemplate>
</asp:FormView>
C# Code -
public partial class Fifthpage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblshow.Text = Request.QueryString["q"].ToString();
Dataset ds = new Dataset();
ds = bind();
da.Fill(ds);
formview1.DataSource = ds;
formview1.DataBind();
}
}
public DataSet bind()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SYSTEM-PC;Initial Catalog=DB;Integrated Security=True";
SqlCommand cmd = new SqlCommand("select * from FireBrigade",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
protected void ddlAddress_DataBound(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = bind();
List<string> ls = new List<string>();
foreach (ListItem lst in ds.Tables[0].Rows)
{
//lst.Value = ds.Tables[0].Rows[0]["Address"].ToString();
ls.Add(ds.Tables[0].Rows[0]["Address"].ToString());
}
DropDownList ddladd = (DropDownList)formview1.FindControl("ddlAddress");
ddladd.DataSource = ls;
}
protected void formview1_ModeChanging(object sender, FormViewModeEventArgs e)
{
formview1.ChangeMode(e.NewMode);
bind();
}
protected void formview1_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
formview1.PageIndex = e.NewPageIndex;
bind();
}
}

You should reassign the DataSource of FormView after editing, so just change your code as follow
protected void formview1_ModeChanging(object sender, FormViewModeEventArgs e)
{
formview1.ChangeMode(e.NewMode);
formview1.DataSource = bind();
formview1.DataBind();
}

Related

OnRowCommand is triggered, OnRowEditing not firing on my gridview

I have a gridview like below:
<asp:GridView ID="gvitems" runat="server" AutoGenerateColumns="false" CssClass="GridStyle" AllowSorting="true" OnSorting="OnSorting" DataKeyNames="Id" OnRowCommand="gv_RowCommand"
OnRowEditing="gv_RowEditing" OnRowUpdating="gv_RowUpdating" OnRowCancelingEdit="gv_RowCancelEdit" >
<Columns>
<asp:buttonfield buttontype="Link"
commandname="View"
text="View"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button runat="server" Text="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Next Steps">
<ItemTemplate>
<asp:Label runat="server" ID="lblNextSteps" Text='<%# Eval("NextSteps")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtNextSteps" Text='<%# Eval("NextSteps")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="txtNextStepsFooter"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the backend, this is how i fill it with data:
DataSet dataSet = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid_SubmittedProjects();
}
}
private void BindGrid_SubmittedProjects(string sortExpression = null)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ProjectsDataBase"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("ViewProjects", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = "myusername";
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
dataSet = new DataSet();
sda.Fill(dataSet, "Project");
}
gvitems.DataSource = dataSet.Tables[0].DefaultView;
gvitems.DataBind();
}
}
}
When I click on the "View" hyperlink on each row, it works, so OnRowCommand function below is triggered.
protected void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
//my work
}
}
However, when I click on "Edit" button, nothing is happening, OnRowEditing is not being triggered.
protected void gv_RowEditing(Object sender, GridViewEditEventArgs e)
{
gvitems.EditIndex = e.NewEditIndex;
this.BindGrid_SubmittedProjects();
}
protected void gv_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
//my update query.
}
I could not see what I am doing wrong. Tried many things I've found over online but none worked. Any help would be so appreciated.
Regards.
Using LinkButton instead of regular button fixed the issue.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>

Cannot find hidden input control on row data bound event

Here is my aspx file content.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<table>
<tr>
<td>
<input id="hdnAID" type="hidden" runat="server" />
<asp:GridView ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound"
DataKeyNames="GeneralSettingID" EnableViewState="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="ItemTemplate" ShowDeleteLink="0" />
</ItemTemplate>
<EditItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="EditItemTemplate" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GeneralSettingID" HeaderText="SettingNo" ReadOnly="true" />
<asp:TemplateField HeaderText="SettingName">
<ItemTemplate>
<asp:Label ID="Label25" runat="server" Text='<%# Eval("GeneralSettingName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingName" onfocus="this.blur();" runat="server" Text='<%# Bind("GeneralSettingName") %>'
Width="350px" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Values">
<ItemTemplate>
<asp:Label ID="Label23" runat="server" Text='<%# Eval("GeneralSettingValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingValue" runat="server" Text='<%# Bind("GeneralSettingValue") %>'
Width="600px" TextMode="MultiLine" Rows="6" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company1">
<ItemTemplate>
<asp:Label ID="Label28" runat="server" Text='<%# Eval("GeneralSettingCompany") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingCompany" runat="server" Text='<%# Bind("GeneralSettingCompany") %>'
Width="100px" TextMode="MultiLine" Rows="1" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company2">
<ItemTemplate>
<asp:DropDownList ID="drpCompanyList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drpCompanyList_SelectedIndexChanged" DataTextField="CompanyName" DataValueField="CompanyID"></asp:DropDownList>
<input id="hdnCompanyId" type="hidden" value='<%# Eval("GeneralSettingCompany") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Here is the .cs side .
private LMSDataAccess.LookupsDataContext LkpDC = new LMSDataAccess.LookupsDataContext(ConfigFile.DBConnStr);
private System.Collections.Generic.List<LMSDataAccess.GeneralSetting> GeneralSettingList = null;
protected void Page_Load(object sender, EventArgs e)
{
base.ModuleID = 27;
if (!IsPostBack)
{
if (Request["AID"] != null)
hdnAID.Value = Request["AID"];
BindData();
}
}
private void BindData()
{
GeneralSettingList = LkpDC.GeneralSettingsGetAll(Common.NVLInt(hdnAID.Value),null).ToList();
GridView1.DataSource = GeneralSettingList;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtUpdateGeneralSettingName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingName");
TextBox txtUpdateGeneralSettingValue = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingValue");
var hdnCompany = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdnCompanyId") as HiddenField;
string KeyValue = GridView1.DataKeys[e.RowIndex].Value.ToString();
LkpDC.GeneralSettingsUpdate(Convert.ToInt32(KeyValue),
txtUpdateGeneralSettingName.Text,
txtUpdateGeneralSettingValue.Text,
Convert.ToInt32(hdnCompany.Value));
GridView1.EditIndex = -1;
BindData();
ResultCode = 0;
}
protected List<LMSDataAccess.Company> GetAllCompanies()
{
System.Collections.Generic.List<LMSDataAccess.Company> CompanyList = null;
LMSDataAccess.OrganizationDataContext OrgDC = new LMSDataAccess.OrganizationDataContext(ConfigFile.DBConnStr);
CompanyList = OrgDC.CompaniesGetAll(null).ToList();
return CompanyList;
}
protected void drpCompanyList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
var hdnCompany = row.FindControl("hdnCompanyId") as HiddenField;
hdnCompany.Value = ddl.SelectedValue;
}
protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = e.Row.FindControl("drpCompanyList") as DropDownList;
//here is the problem.
var hdn = e.Row.FindControl("hdnCompanyId") as HiddenField;
if (ddl != null)
{
ddl.DataSource = GetAllCompanies();
ddl.DataValueField = "CompanyID";
ddl.DataTextField = "CompanyName";
ddl.DataBind();
}
}
}
My beloved problem is not being able to get hdnCompanyId element when GridView1_RowDataBound and drpCompanyList_SelectedIndexChangedfired.I am always getting null.(as showed at the commented line )
I have tried under GridView1_RowDataBound event method like e.Row.FindControl("hdnCompanyId")
but it did not work.
My final aim is to setting and getting this element to control selected items of my dropdownlist.
I think the code is well written but I guess I am missing something about hierarchy of the user control elements.
Can you help me about what I am missing?
I have found that the problem was choosing the wrong casting type of the input.It must be HtmlInputHidden rather than HiddenField.I hope someone can get useful info from that question.

How to preserve value of textboxes using TemplateFields in GridView

I have a GridView that lists data from my mysql database table. In addition, I created two TemplateFields to the GridView. The first TemplateField displays the data from database tables and the second TemplateView contains 1x asp:TextBox (a.k.a quantity) and 2x asp:Buttons (a.k.a +/- buttons which change the value inside the quantity TextBox. In addition to binding the GridView on PageLoad event, I also have a search TextBox which filters the rows displayed in the GridView. Here is the code behind for the search GridView TextBox:
private void SearchProducts()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand())
{
string sql = "SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products";
if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
{
sql += " WHERE description LIKE " + "'%" + txtSearch.Text + "%'";
}
cmd.CommandText = sql;
cmd.Connection = con;
using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY"));
GridView1.DataBind();
//TextBox qty4 = GridView1.FindControl("qty_ordered") as TextBox;
// for(int i = 0; i < GridView1.Rows.Count; i++)
//{
// Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
// TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
// if (ViewState["purchased"] != null)
// {
// qty2.Text = ViewState["purchased"].ToString();
// }
// //test222.Text = qty2.Text;
//}
}
}
}
//foreach(GridViewRow rows in GridView1.Rows)
{
//Label test22 = rows.FindControl("test2") as Label;
//TextBox qty = rows.FindControl("qty_ordered") as TextBox;
//if (ViewState["purchased"] != null)
//{
//qty.Text = ViewState["purchased"].ToString();
//}
}
}
First I tried saving each Rows TextBox.Text to ViewState but wasn't successful, then I tried dynamically adding a new column to DataTable before DataBind() but that also went south... The Buttons (+/-) and TextBox work fine when PostBack is from the buttons themselves. However, as soon as I filter the GridView using the c# code above, The TextBoxes all turn back to "0" and lose their values. I think that adding the new column dynamically is the way to go, I'm just not sure how to save/update the values without creating EditTemplateFields.
Here is my asp.net code for the GridView:
<asp:GridView id="GridView1" EnableViewState="true" AutoGenerateColumns="false" PageSize="100" ShowHeader="false" DataKeyNames="logic_code" AllowPaging="true" runat="server" Style="width:100%;margin-top:45px;">
<Columns>
<asp:BoundField DataField="QUANTITY" runat="server" readonly="true" />
<asp:TemplateField HeaderText="Product_Template" runat="server">
<ItemTemplate>
<asp:label id="supplier_number" runat="server" Style="font-weight:bold;font-size:28px;" Text='<%# Eval("supplier_number")%>' /> <asp:label id="total_inventory" runat="server" Text='<%# Eval("total_inventory")%>' Style="float:right;" />
<br />
<asp:label id="sequence" runat="server" Text='<%# Eval("sequence")%>' Style="float:right;" />
<br />
<asp:Image id="product_image" runat="server" Height="320px" Width="320px" ImageUrl='<%# Eval("image_location")%>' />
<br />
<asp:label id="product_description" runat="server" Text='<%# Eval("description")%>' Style="white-space:nowrap;" /> &nbsp<asp:label id="unit_of_price" runat="server" Text='<%# Eval("unit_of_price")%>' Style="float:right;font-size:10px;margin-top:16px;margin-right:5px;margin-left:1px;" /><asp:label id="price_pref" runat="server" Text='<%# "$" + Eval("price_pref")%>' Style="float:right;font-size:22px;font-weight:bold;" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product_Template1" runat="server" ItemStyle-Width="150px">
<ItemTemplate runat="server">
<asp:Button id="add" runat="server" Text="+" Width="45px" Style="float:right;" OnClick="addClicked" autopostback="true" UseSubmitBehavior="true"></asp:Button> <asp:Button id="subtract" runat="server" Text="-" Style="float:right;" OnClick="subtractClicked" autopostback="true" UseSubmitBehavior="true" Width="45px"></asp:Button>
<asp:TextBox id="qty_ordered" runat="server" Text="0" Enabled="false" Style="float:right;" Width="57px" EnableViewState="true" ReadOnly="true" />
<asp:Label id="unit_display" runat="server" Style="float:right;" />
<asp:Label id="sequenceID" runat="server" Text='<%# Eval("sequence")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_code1" runat="server" Text='<%# Eval("unit_code")%>' Visible="false" Enabled="false" />
<asp:Label id="supplier_no" runat="server" Text='<%# Eval("supplier_number")%>' Visible="false" Enabled="false" />
<asp:Label id="total_inventory1" runat="server" Text='<%# Eval("total_inventory")%>' Visible="false" Enabled="false" />
<asp:Label id="logic_code1" runat="server" Text='<%# Eval("logic_code")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_of_price1" runat="server" Text='<%# Eval("unit_of_price")%>' Visible="false" Enabled="false" />
<asp:Label id="price_pref1" runat="server" Text='<%# Eval("price_pref")%>' Visible="false" Enabled="false" />
<asp:Label id="special_price1" runat="server" Text='<%# Eval("special_price")%>' Visible="false" Enabled="false" />
<asp:Label id="description1" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="tester" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="test2" runat="server" Visible="true" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the code behind for how I populate the GridView on PageLoad when the GridView is not getting filtered by the search box:
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products"))
{
using (MySqlDataAdapter da = new MySqlDataAdapter())
{
cmd.Connection = con;
da.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
da.Fill(dt);
GridView1.DataSource = dt;
dt.Columns.Add(new DataColumn("QUANTITY", System.Type.GetType("System.Double")));
GridView1.DataBind();
con.Close();
}
}
}
}
}
And PageLoad is here:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
if (string.IsNullOrEmpty(txtSearch.Text))
{
//txtSearch.Attributes.Add("CssStyle", "cursor");
txtSearch.Attributes.Add("placeholder", " Showing All Products");
}
//foreach(GridViewRow row in GridView1.Rows)
//{
// if (IsPostBack)
// {
// if (ViewState["purchased"].ToString() != null)
// {
// qty.Text = ViewState["purchased"].ToString();
// }
// }
//}
}
I also have EnableViewState = "true" at the top of page.
***Note: with the code below on each button (+/-), the ViewState seems to save fine as my labels get populated appropriately by reading the ViewState even when postback. However, the values of the labels (ViewState value) get reset once I call the private void SearchProducts()
for(int i = 0; i < GridView1.Rows.Count; i++)
{
Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
ViewState["purchased"] = qty2.Text;
test222.Text = ViewState["purchased"].ToString();
}
and heres 2 snapshots: (as you can see, when I enter "Benus" inside the search textbox, the gridview gets filtered correctly, but all the TextBox values gets reset to "0")

Why is the Update Control of Gridview is behaving abnormally?

Here is my code for updating the gridview rows. But what it does it shows this behavior which I guess is not what it usually does. Please point out what did I do wrong.
This is an image showcasing what is happening.
The code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindgrid();
}
}
private void bindgrid()
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from vendor";
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
And this is ASPX code:
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit Element" CssClass="btn btn-success fa fa-edit" ID="Editbutton" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" CssClass="btn btn-success fa fa-edit" ID="updatebutton" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" CssClass="btn btn-warning fa fa-close" ID="cancelbutton" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%# Eval("v_id")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="idtext" runat="server" Text='<%# Eval("v_id")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor Name">
<ItemTemplate>
<asp:Label ID="namelbl" runat="server" Text='<%# Eval("v_name")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nametext" runat="server" Text='<%# Eval("v_name")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

Gridview update button

I have a GridView with a button which sets all rows into edit mode (which is what I want). However I was wondering if there is a way to create a button that will update the whole gridview with my changes. Here is the code behind this.
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
onrowcommand="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="labelID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat="server" Text='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="labelfirstname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
<asp:TextBox ID="txtFirstName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="labellastname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
<asp:TextBox ID="txtLastName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Edit Mode" onclick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" Text="View Mode" onclick="Button2_Click1" />
And here is the c#
private bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname FROM Company", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
isEditMode = true;
BindData();
}
protected void Button2_Click1(object sender, EventArgs e)
{
isEditMode = false;
BindData();
}
Thank you in advance!!
You can iterate thru you rows and get values in a textbox for specific row
foreach (GridViewRow row in gvUsers.Rows)
{
TextBox txtFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox txtLastName = row.FindControl("txtLastName") as TextBox;
if (txtFirstName.Text!="" && txtLastName.Text!="")
{
// do what you need with values
}
}

Categories

Resources