Gridview binding clears unexpectedly - c#

I have a problem with my gridview. I have searched alot for the solution but can't find any answers. I think I have located the problem to be that the gridview is no longer bound when I press the update button - which results in null values. I thought it was enough to bind at RowEditing. Where else can I bind my gridview?
See the markup below:
<asp:GridView ID="ProductGridView" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Id" OnRowEditing="ProductGridView_RowEditing"
OnRowCancelingEdit="ProductGridView_RowCancelingEdit" OnRowUpdating="ProductGridView_RowUpdating"
OnRowDeleting="ProductGridView_RowDeleting" OnDataBound="ProductGridView_DataBound" OnRowDataBound="ProductGridView_RowDataBound">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" CausesValidation="false" />
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<EditItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Quantity") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Family" SortExpression="Family.Name">
<EditItemTemplate>
<asp:DropDownList ID="ddlFamily" runat="server" OnInit="ddlFamily_Init">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFamily" runat="server" Text='<%# Eval("Family.Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGridView(_productRepo.GetAll());
}
}
private void BindGridView(object source)
{
ProductGridView.DataSource = source;
ProductGridView.DataBind();
}
protected void ProductGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ProductGridView.EditIndex = e.NewEditIndex;
BindGridView(_productRepo.GetAll()); // GetAll returns an IEnumerable.
rowCount = ProductGridView.Rows.Count; // Count is 6 here, which is correct.
}
protected void ProductGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
rowCount = ProductGridView.Rows.Count; // Count is 0 here.
//BindGridView(_productRepo.GetAll()); // Tried to rebind which works but getting the old values obviously.
//rowCount = ProductGridView.Rows.Count; // Count is 6 here.
// Get the controls - all is null. Works ok when I use BindGridView above.
TextBox txtName = FindChildControl<TextBox>(this.Page, "txtName");
TextBox txtQuantity = FindChildControl<TextBox>(this.Page, "txtQuantity");
DropDownList ddlFamily = FindChildControl<DropDownList>(this.Page, "ddlFamily");
// More code to populate a new product and bind the gridview again etc.
}
I also have a RowDataBound method. Can this contribute to the problem?
protected void ProductGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlFamily");
ddl.DataSource = _familyRepo.GetAll().Select(f => f.Name);
ddl.DataBind();
Product product = _productRepo.FindSingle(p => p.Id == (int)ProductGridView.DataKeys[e.Row.RowIndex].Value);
ddl.SelectedIndex = (int)product.FamilyID - 1;
}
}

If I understand you correctly, you are saying your form controls within your datagrid disappear or reset to their initial state after postback.
The reason this is happening is because you are binding your grid in the Page_Load method, which comes too late in the page lifecycle to restore the control values. Your grid doesn't load until AFTER the LoadViewstate and LoadPostbackData events are fired and therefore, your grid's controls are loaded with their original state every time a postback is made.
I'd guess you're familiar with the asp.net lifecycle, but if not here is an article: http://msdn.microsoft.com/en-us/library/ms972976.aspx. I've dealt with this issue many times, and it took me awhile to fully understand what was going on here.
One solution to the problem is to load the grid in the overridden OnInit method, which occurs before the control data is restored. Something like this should work:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
BindGridView(_productRepo.GetAll());
}

I usually do data binding this way.... try this function and call it in your page load and other functions where you need it.
protected void bind()
{
con.Open();
SqlCommand cmd = new SqlCommand("Your Query", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
gvCourse.DataSource = ds;
gvCourse.DataBind();
con.Close();
}

Or you can simply replace the !Page.IsPostBack with !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView(_productRepo.GetAll());
}
}

Related

Can't update a column in a GridView with a DropDownList in its EditItemTemplate

I'm trying to do a simple To-Do list application in ASP.NET with C# and I have a problem when I want to update the GridView with a value from a DropDownList. I've read a lot of solved question about this problem on this site but none of them worked so far or I must have missed something. Based on those answers I tried 2 method:
Method: I added a GridView to display and a FormView to add the Tasks. I created a database with a table for Tasks with Id, Name, Priority, DueDate, Completed columns and one table for priority possibilities(Low-Medium-High)
My code looks this was:
ASP.NET GridView part:
<asp:GridView ID="grdTasks" runat="server" AutoGenerateColumns="False" OnRowDataBound="grdTasks_RowDataBound" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" OnRowEditing="grdTasks_RowEditing" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" OnRowCancelingEdit="grdTasks_RowCancelingEdit" OnRowUpdating="grdTasks_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Id">
<EditItemTemplate>
<asp:TextBox ID="txtId" runat="server" Text='<%# Bind("Id") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Priority">
<EditItemTemplate>
<asp:DropDownList ID="ddlPriority" runat="server" AppendDataBoundItems="True">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblPriority" runat="server" Text='<%# Bind("Priority") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DueDate" HeaderText="DueDate" />
<asp:TemplateField HeaderText="Completed">
<EditItemTemplate>
<asp:Checkbox ID="chkCompleted" runat="server" Text='<%# Bind("Completed") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="txtCompleted1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
C# part:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindTasks();
}
}
private void BindTasks()
{
SqlDataSource sqlDtsTasks = new SqlDataSource();
sqlDtsTasks.ID = "sqlDtsTasks";
this.Page.Controls.Add(sqlDtsTasks);
sqlDtsTasks.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
sqlDtsTasks.SelectCommand = "SELECT * FROM Tasks";
grdTasks.DataSource = sqlDtsTasks;
grdTasks.DataBind();
}
protected void grdTasks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlPriority =
(DropDownList)e.Row.FindControl("ddlPriority");
SqlDataSource sqlDtsTasks = new SqlDataSource();
SsqlDtsTasks.ID = "sqlDtsTasks";
this.Page.Controls.Add(sqlDtsTasks);
sqlDtsTasks.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
sqlDtsTasks.SelectCommand = "SELECT [States] FROM [Reference]";
ddlPriority.DataSource = sqlDtsTasks;
ddlPriority.DataTextField = "States";
ddlPriority.DataValueField = "States";
ddlPriority.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
ddlPriority.SelectedValue =
dr["Priority"].ToString();
}
}
}
protected void grdTasks_RowEditing(object sender, GridViewEditEventArgs e)
{
grdTasks.EditIndex = e.NewEditIndex;
BindTasks();
}
protected void grdTasks_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdTasks.EditIndex = -1;
BindTasks();
}
protected void grdTasks_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlDataSource sqlDtsTasks = new SqlDataSource();
sqlDtsTasks.ID = "sqlDtsTasks";
this.Page.Controls.Add(sqlDtsTasks);
sqlDtsTasks.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string Priotext = (grdTasks.Rows[e.RowIndex].Cells[2].FindControl("ddlPriority") as DropDownList).SelectedItem.Value;
string Id = (grdTasks.Rows[e.RowIndex].Cells[0].FindControl("txtId") as TextBox).Text;
sqlDtsTasks.UpdateCommand = "UPDATE Tasks SET [Priority] = #Priority WHERE [Id] = #Id";
--> SqlDataSource2.UpdateParameters["Id"].DefaultValue = Id;
--> SqlDataSource2.UpdateParameters["Priority"].DefaultValue = Priotext;
grdTasks.DataSource = sqlDtsTasks;
grdTasks.DataBind();
}
This way I get the following error from the line marked with the arrow:
System.NullReferenceException - Object reference not set to an instance of an object.
This should mean that I got a null value from the ddl and the textbox but I dont know why, when I try to display the values of the ddl and textbox with a label, it displays it correctly.
Method: I basically did the same, but instead of doing it from code, I added 2 SqlDataSource. The first is binded to the GridView to display the Tasks. The second is binded to the DropDownList to display the Priority possibilities(Low-Medium-High). Also, I used the DataBindings from the smart tag of the DropDownList to bind the SelectedValue to the Priority column. This way, I can choose a priority when editing the row and I can update the Priority column if the current value in the db is null. BUT, when I want to update again, e.g. from Low to High I get this error:
System.ArgumentOutOfRangeException 'ddlPriority' has a SelectedValue which is invalid because it does not exist in the list of items.
As I've read about this many people pointed out that I should add a code like this and set the AppendDataBoundItems to true:
"<asp:ListItem Value=""></asp:ListItem>"
I even tried to add a line for each value like the one above, still the same error. What do I missing?

Gridview is not displaying while i run my code

I want to display three column field as dropdownlist and other in textbox format.I have wrote the code to display the dropdownlist value from my database but its not working.I have attached my code for your referal
<asp:GridView ID="Gv1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="FacultyName">
<ItemTemplate>
<asp:Label ID="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false" />
<asp:DropDownList ID="ddlfaculty" runat="server" OnSelectedIndexChanged="ddlfaculty_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("subject") %>>' Visible="false" />
<asp:DropDownList ID="ddlsubject" runat="server" OnSelectedIndexChanged="ddlsubject_SelectedIndexChanged1"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblsubject" runat="server" Text='<%%# Eval("sethour") %>>' Visible="false" />
<asp:TextBox ID="ddlsethour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblcount" runat="server" Visible="false" />
<asp:TextBox ID="Count" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind:
public partial class transhonorarium : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlfaculty_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select facultyname from faculty", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
protected void ddlsubject_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
SqlDataAdapter cmd = new SqlDataAdapter("select subject from assign where facultyname=#facultyname", con);
DataTable dt = new DataTable("dt");
cmd.Fill(dt);
Gv1.DataSource = dt;
Gv1.DataBind();
}
}
}
You need to change one thing here.
AutoGenerateColumns = true. Because of this, you will be able to see the columns assigned and its data.
Secondly,
You need to Bind your Gridview as required on Page_load or somewhere you want. Here is for page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Gv1.DataSource = Somesource;
Gv1.DataBind();
}
}
See the Bind Data
public void BindData()
{
SqlCommand comd = new SqlCommand("SELECT * FROM Yourtablename", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GV1.DataSource = dt;
GV1.DataBind();
}
Hope that helps
Call the DataBind() Method of your Gridview when your data changes.
I'd do something like this:
protected override void OnPreRender(Eventargs e)
{
base.OnPreRender(e);
GV1.DataBind();
}
in order to fill your dropdown lists ,you should implement _RowDataBound event and to update dataset bases on your selection you should also implement RowCommand event for your dropdown objects.
btw. in ddlsubject_SelectedIndexChanged, you also need to add parameter to your sql command to get your sql string working ,
hope this helps.

transfer data from gridview to another webform in asp.net using c#?

i have a gridview like this :
<asp:GridView ID="wbsdataGV1" runat="server" Width="790px" AutoGenerateColumns="False"
OnSelectedIndexChanged="wbsdataGV1_SelectionChanged">
<Columns>
<asp:TemplateField HeaderText="WBS Code">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("WBSCode") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="TextBox7" runat="server" Text='<%# Eval("Description") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Territory Code">
<ItemTemplate>
<asp:TextBox ID="TextBox8" runat="server" Text='<%# Eval("TerritoryCode") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="TextBox9" runat="server" Text='<%# Eval("AmountReleased") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
when i am clicking on the linkbutton i want that data and i will transfer that to another aspx from .. through
protected void wbsdataGV1_SelectionChanged(object sender, EventArgs e)
{
//Some code ;
}
now my question is how i can get that data by clicking the linkbutton on gridview ? i can transfer the data by querystring or session variable or hidden text field ... but my concern is that how can i get the exact clicked data...
any help?
Define the DataKeys attribute to the be primary key of your data (here I assume you have a row identifier called "ID".
<asp:GridView ... DataKeys="ID">
... existing markup
</asp:GridView>
In wbsdataGV1_SelectionChanged, get back the ID of the row the user clicked like this:
int rowID = (int)this.wbsdataGV1.SelectedDataKey.Value;
Then redirect to another page like this, passing just the ID:
Response.Redirect("anotherpage.aspx?id=" + rowID);
Then in your other page:
protected void Page_Load(object s, EventArgs e)
{
if (!Page.IsPostback)
{
int rowID = int.Parse(Request.QueryString["id"]);
// do something with the ID of the row, like go and look
// up JUST that row again
}
}
Bonus - to make the whole row clickable, avoiding the need for a CommandButton, do this:
<script language="javascript" type="text/javascript">
var oldColour = null;
function rowMouseover(o) {
o.style.cursor = 'pointer';
oldColour = o.style.backgroundColor;
o.style.backgroundColor = '#dddddd';
}
function rowMouseout(o) {
o.style.backgroundColor = oldColour;
}
</script>
<asp:GridView ... OnRowCreated="grid_RowCreated" />
protected void grid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] =
Page.ClientScript.GetPostBackClientHyperlink(
this.grid,
"Select$" + e.Row.RowIndex);
e.Row.Attributes["onmouseover"] = "rowMouseover(this);";
e.Row.Attributes["onmouseout"] = "rowMouseout(this);";
}
}
protected override void Render(HtmlTextWriter writer)
{
for (int i = 0; i < grid.Rows.Count; i++)
Page.ClientScript.RegisterForEventValidation(grid.UniqueID, "Select$" + i);
base.Render(writer);
}
You could pass the ID via the Session object, but you'd get odd behaviour with more than one browser window doing the same operation at the same time (depending on the browser). This would be hard for a user to tamper with.
You could pass the ID via Request.Form too, that would hide it from trivial user fiddling but doesn't add any true security.
Protip: don't just dump massive objects into the Session variable. It's lazy, error prone, and doesn't scale.

ASP.NET GridView RowCommand TextBox empty

Hi I have a grid view with a textbox in each row that im trying to get the value of in the RowCommand event. The below code works fine for all rows expect the first one. The textbox.text value for the first row in always empty.
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_OnRowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
Title <%# Eval("Title")%>
<asp:TextBox ID="TextBoxAddPost" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("postId") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
bindGridView();
}
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddPost")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox textBox = (TextBox)row.FindControl("TextBoxAddPost");
//Empty for first row but works for all others
Debug.WriteLine("row: " + row.RowIndex + ", textBox:" + textBox.Text.Trim());
GridView1.DataBind();
}
}
The above code has been simplified for illustration purposes. Each row actually contains a child gridview, hence why in need the text box in each row. I fear that the binding in the page_load is overwriting the value of the text box, however, without the page_load binding, the rowCommand Event is not fired.
I find i a bit strange the it works fine for all rows except the first.
For getting data from textbox, You have to set text property first by putting below code.
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("Title") %>'></asp:TextBox>
It will definitely give value from textbox.
Either way, You can also set datakeynames property of gridview.Click here for datakeynames
I tried this and it works fine,GridView1_OnRowCommand fires by clicking on LinkButtonAddPost:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxAddPost" runat="server" Text='<%# Eval("ID") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButtonAddPost" CommandName="AddPost" CommandArgument='<%# Eval("ID") %>' runat="server">Add Post</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and change your page_load event like this:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = Data.RequestPaymentDB.GetRequestPaymentByRequestID(9208060001);
GridView1.DataBind();
}
compare your code with mine.

Does not appear to be emitting correct GridView markup for __doPostBack

I asked this question regarding a strange behaviour from a GridView control in ASP.Net (I'm using C#).
For each row in my GridView there is an an 'Edit' and 'Delete' link. The edit for example has this javascript:__doPostBack('gvwServers','Edit$0') - So obviously the server is going to figure out someone has clicked to edit row 0 of gvwServers.
Fair enough. If I click the Edit link I get a postback and the GridView is redrawn with the Edit button replaced with an 'Update' and 'Cancel' button. Standard behaviour. NOW - The 'Cancel' button has this link javascript:__doPostBack('gvwServers','Cancel$0') - just what I would expect Cancel row 0 of gvwServers. BUT The Update button has javascript:__doPostBack('gvwServers$ctl02$ctl00',''). This appears to not make any sense. And this appears to be the cause of my routine to handle Update not being fired.
Why is ASP not outputting the correct postback arguments?
My code is available at the link above.
<asp:GridView ID="gvwServers" runat="server" class="gvwServers"
AutoGenerateColumns="false" OnRowEditing="gvwServers_Edit"
onrowcancelingedit="gvwServers_Cancelling" onrowdeleting="gvwServers_Deleting"
onrowupdated="gvwServers_Updated" onrowupdating="gvwServers_Updating"
AutoGenerateEditButton=true AutoGenerateDeleteButton=true>
<columns>
<asp:CommandField ShowEditButton="true" />
<asp:CommandField ShowDeleteButton="true" />
<asp:BoundField DataField="intServerID" visible="false" />
<asp:TemplateField HeaderText = "Server Name">
<ItemTemplate>
<asp:Label ID="lblServerName" runat="server" Text='<%# Bind("txtName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtServerName_Edit" runat="server" Text='<%# Bind("txtName") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Key">
<ItemTemplate>
<asp:Label ID="lblAppKey" runat="server" Text='<%# Bind("txtApplicationKey") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAppKey_Edit" runat="server" Text='<%# Bind("txtApplicationKey") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "Connection String">
<ItemTemplate>
<asp:Label ID="lblConnString" runat="server" Text='************'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtConnString_Edit" Width="300px" Height="100px" Text='<%# Bind("txtConnectionString")%>' TextMode="MultiLine" ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
Not sure what you're expecting/not happening. I took your gridview code and used your code behind in the other link. I added a Response.Write in each handler and it seems to run as expected.
public class Item
{
public int intServerID { get; set; }
public string txtName { get; set; }
public string txtApplicationKey { get; set; }
public string txtConnectionString { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Item item = new Item();
item.intServerID = 1;
item.txtName = "Apple";
item.txtApplicationKey = "Orange";
item.txtConnectionString = "Test";
List<Item> items = new List<Item>();
items.Add(item);
gvwServers.DataSource = items;
gvwServers.DataBind();
}
protected void gvwServers_Edit(object sender, GridViewEditEventArgs e)
{
Response.Write("Edit");
gvwServers.EditIndex = e.NewEditIndex;
gvwServers.DataBind();
}
protected void gvwServers_Updated(object sender, GridViewUpdatedEventArgs e)
{
Response.Write("Updated");
gvwServers.DataBind();
}
protected void gvwServers_Updating(object sender, GridViewUpdateEventArgs e)
{
Response.Write("Updating");
gvwServers.DataBind();
}
protected void gvwServers_Deleting(object sender, GridViewDeleteEventArgs e)
{
Response.Write("Delete");
gvwServers.DataBind();
}
protected void gvwServers_Cancelling(object sender, GridViewCancelEditEventArgs e)
{
Response.Write("Cancel");
e.Cancel = true;
gvwServers.EditIndex = -1;
gvwServers.DataBind();
}

Categories