GridView row won't disable - c#

I am trying to disable a specific grdview row using the code below, but it isn't disabling that row. I am 100% sure there is a value called "Total Expenses" in the column that is bound to the gridview. What is more strange is that, I removed the if condition(accountTextBox.Text == "Total Expenses") to see if all the rows get disabled but only the first row is getting disabled. Any thoughts on this?
More information: Am using gridview with template fields(ASP.NET, C#). I also ran debugger and found that the accountTextBox is showing NULL. Am puzzled!
I appreciate any thoughts you may have. Thank you
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
originalDataTable = ((System.Data.DataRowView)e.Row.DataItem).Row.Table.Copy();
ViewState["originalValuesDataTable"] = originalDataTable;
tableCopied = true;
TextBox accountTextBox = (TextBox)e.Row.FindControl("AccountTextBox");
if (accountTextBox.Text == "Total Expenses")
{
e.Row.Enabled = false;
}
}
}

I'm assuming your markup looks something like this:
<asp:TemplateField HeaderText="SomeField" SortExpression="SomeField">
<EditItemTemplate>
<asp:TextBox ID="AccountTextBox" runat="server" Text='<%# Bind("SomeField") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("SomeField") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In which case AccountTextBox will only be available in RowDataBound when e.Row.State is in Edit mode. which may or may not be available depending what update functionality is provided in your datasource...but that's something else.
Typically you don't use a TextBox to display data but lets say trying to populate a "readonly" TextBox then all you need do is move AccountTextBox from the EditTemplate to the ItemTemplate and you should be good to go.

Using the following code-behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gvTest.DataSource = new List<string>() { "test1", "test2" };
gvTest.DataBind();
}
private bool tableCopied = false;
private System.Data.DataTable originalDataTable;
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
//originalDataTable = ((System.Data.DataRowView)e.Row.DataItem).Row.Table.Copy();
//ViewState["originalValuesDataTable"] = originalDataTable;
//tableCopied = true;
TextBox accountTextBox = (TextBox)e.Row.FindControl("AccountTextBox");
if (accountTextBox.Text == "Total Expenses")
{
e.Row.Enabled = false;
}
}
}
}
And this markup:
<asp:GridView runat="server" ID="gvTest" OnRowDataBound="gvTest_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="AccountTextBox" runat="server">Total Expenses</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am not reproducing the bug. Both rows disable for me.

The tableCopied variable could be the problem. It will be set to true on the first row and this will restrict the remaining rows to enter the if condition and actually be disabled.
First row:
//tableCopied is false
if(!tableCopied) // pass
tableCopied = true
Other rows:
//tableCopied is true
if(!tableCopied) // wont pass
Note that the GridView1_RowDataBound event occurs once for every row on the same postback and every class member is persisted during the postback.

Related

gridview findcontrol returning nothing empty string(Blank)

I am trying to pass a session value from a gridview select row using GridView1_RowEditing1 event. i am able to get session value for primarykey (p.key) but the Associate_ID returns empty.
C# Code behind
protected void GridView1_RowEditing1(object sender, GridViewEditEventArgs e)
{
int primarykey = Convert.ToInt32(GridView1.DataKeys[e.NewEditIndex].Value);
string name = Convert.ToString(GridView1.Rows[e.NewEditIndex].FindControl("Associate_ID"));
Session["Number"] = primarykey;
Session["Name"] = name;
//redirect
Response.Redirect("updatee.aspx");
}
.ASPX
<asp:TemplateField HeaderText="Associate_ID" SortExpression="Associate_ID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
OUTPUT:
Key: 5
Name:
As you can see i am not getting Associate_ID for selected field.
Also tried using
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("Associate_ID"));
but there was no result, the grid has multiple columns and rows (8*15)
tried suggestions on gridview findcontrol returning empty "" and tried stopping re-binding the GridView on the PostBack.
removed DataSourceID from gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//DataSourceID = "SqlDataSource1"
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
None of this helped. I am still getting a blank value for Associate_ID.
i am unable to see where the issue is. Please help!
You are trying to find the Control Associate_ID with FindControl. But it does not exist. Either find TextBox1 or rename the TextBox to Associate_ID.
<EditItemTemplate>
<asp:TextBox ID="Associate_ID" runat="server" Text='<%# Bind("Associate_ID") %>'></asp:TextBox>
</EditItemTemplate>
//or
string name = Convert.ToString(GridView1.Rows[3].Cells[3].FindControl("TextBox1"));
UPDATE
I see the problem, somehow you are trying to access those control before the edit state has been activated by rebinding the GridView. The edit index has not been set. So place this before the FindControl.
GridView1.DataSource = yourSource;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
Thank you so much VDWWD, i was finally able to get it to work.
The problem was i was not able to use get my 'TextBox' element in gridview using FindControl.
The solution was to not re-binding the GridView on the PostBack of the page and edit index on the RowEditing event.
This is what my working code looks like, is any one ever comes across a similar issue
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.DataSource = SqlDataSource1;
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
TextBox txt = GridView1.Rows[e.NewEditIndex].FindControl("TextBox1") as TextBox;
string name = txt.Text;
}
.ASPX
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryName") %>'></asp:TextBox>
</EditItemTemplate>

Can't read Label value in GridView

I have read many posts here looking for the answer. But no matter what I do I always get a null value returned for my Label.
I can populate it just fine and read it at that time, but when I try to read the label to populate DB it is always null.
aspx code:
<asp:TemplateField HeaderText="TOTAL YIELD" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="130">
<EditItemTemplate>
<asp:Label ID="lb_TotalYield" runat="server" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
in the code behind I am just trying to read it.
foreach (GridViewRow currentRow in gv_Fruit.Rows)
{
Label tempLabel = (Label)currentRow.FindControl("lb_TotalValue") as Label;
string theTotalValue = tempLabel.Text;
}
for complete information Here is how I set the label:
myGridView.SelectedRow.Cells[4].Text = myTotalYield;
I have tried doing a gv_RowDataBound, but it doesn't seem to ever be called.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (myGridView.EditIndex == e.Row.RowIndex &&
e.Row.RowType == DataControlRowType.DataRow)
{
Label mylabel = (Label)e.Row.FindControl("lb_TotalYield");
mylabel.DataBind();
}
}

Unable to delete multiple grid view records

I am trying to delete multiple grid view records. I tried as shown below.
public void btnDelete_Click(object sender, EventArgs e)
{
StringCollection orderNumberCollection = new StringCollection();
if (gridOrders.Rows.Count > 0)
{
foreach (GridViewRow gvrow in gridOrders.Rows)
{
if (gvrow.RowType == DataControlRowType.DataRow) {
CheckBox cbx = (CheckBox)gvrow.Cells[0].FindControl("chkdelete");
Label lblOrderNumner = (Label)gvrow.FindControl("labelOrderNumber");
Label lastName = (Label)gvrow.FindControl("LabelLastName");
if (cbx.Checked && lblOrderNumner != null)
{
orderNumberCollection.Add(lblOrderNumner.Text);
}
}
}
}
if (orderNumberCollection.Count > 0)
{
DeleteMultipleOrders(orderNumberCollection);
}
}
But always check box control showing "Checked = false". Why check box control always showing false even I checked some of the check boxes?
Here is my Grid view code:
<asp:TemplateField>
<HeaderTemplate>
<table><tr><td ><asp:CheckBox ID="chkAll" runat="server" /></td><td><asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" /></td></tr></table>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" Text='<%# Bind("OrderNumber") %>' Font-Bold="false" />
</ItemTemplate>
</asp:TemplateField>
I'm with Tim on this, it sounds like you are loading your gridview from within Page_Load, which is fine. but in your case you would need to make sure your gridview loading code looks like this:
if(!Page.IsPostBack)
{
//gridview loading code
}
this prevents your gridview from being reloaded (and losing which boxes are checked) when you click your delete button

Dynamically added controls missing during GridView RowUpdating

I have a GridView with a TemplateField column that I put PlaceHolder controls in. During the DataBound event for the GridView I dynamically add a few CheckBoxes to the PlaceHolder. That works fine and displays as expected.
My problem is that during the RowUpdating event the PlaceHolder contains no controls; my CheckBoxes are missing. I also noticed that they're missing during the RowEditing event.
I want to be able to get the values of the CheckBoxes during the RowUpdating event so I can save them to the database.
Here's some example code. I've trimmed out a lot to reduce size, but if you want to see specifics just ask and I'll be happy to add more.
HTML:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False"
ondatabound="gridView_DataBound" onrowupdating="gridView_RowUpdating"
onrowediting="gridView_RowEditing" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
<EditItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="updateButton" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
// This method works fine, no obvious problems here.
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder)row.FindControl("countriesPlaceHolder");
// Create a CheckBox for each country and add it to the PlaceHolder
foreach (Country country in this.Countries)
{
bool isChecked = holidays.ElementAt(i).Countries.Any(item => item.ID == country.ID);
var countryCheckBox = new CheckBox
{
Checked = isChecked,
ID = country.Abbreviation + "CheckBox",
Text = country.Abbreviation
};
placeHolder.Controls.Add(countryCheckBox);
}
}
}
protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = gridView.Rows[e.NewEditIndex].FindControl("countriesPlaceHolder").Controls;
gridView.EditIndex = e.NewEditIndex;
BindData();
}
protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// EXAMPLE: I'm expecting checkBoxControls to contain my CheckBoxes, but it's empty.
var checkBoxControls = ((PlaceHolder)gridView.Rows[e.RowIndex].FindControl("countriesPlaceHolder")).Controls;
// This is where I'd grab the values from the controls, create an entity, and save the entity to the database.
gridView.EditIndex = -1;
BindData();
}
This is the article that I followed for my data binding approach: http://www.aarongoldenthal.com/post/2009/04/19/Manually-Databinding-a-GridView.aspx
You need to call your BindData() method on page load.
"Dynamic controls or columns need to be recreated on every page load, because of the way that controls work. Dynamic controls do not get retained so you have to reload them on every page postback; however, viewstate will be retained for these controls."
See Cells in gridview lose controls on RowUpdating event
Also in the article you linked, there is an ItemTemplate and an EditItemTemplace because they have different displays, i.e. read only and editable. Yours are the same so I think you could simplify your design:
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ondatabound="gridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Countries">
<ItemTemplate>
<asp:PlaceHolder ID="countriesPlaceHolder" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="editButton" runat="server" Text="Edit" onclick="editButton_Click" ></asp:LinkButton>
<asp:LinkButton ID="updateButton" runat="server" Text="Update" onclick="updateButton_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind:
protected void gridView_DataBound(object sender, EventArgs e)
{
// Loop through the Holidays that are bound to the GridView
var holidays = (IEnumerable<Holiday>)gridView.DataSource;
for (int i = 0; i < holidays.Count(); i++)
{
// Get the row the Holiday is bound to
GridViewRow row = gridView.Rows[i];
// Get the PlaceHolder control
var placeHolder = (PlaceHolder) row.FindControl("countriesPlaceHolder");
var countryCheckBox = new CheckBox
{
Checked = true,
ID = "auCheckBox",
Text = "Aus",
Enabled = false
};
placeHolder.Controls.Add(countryCheckBox);
var editButton = (LinkButton)row.FindControl("editButton");
editButton.CommandArgument = i.ToString();
var updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.CommandArgument = i.ToString();
updateButton.Visible = false;
}
}
protected void editButton_Click(object sender, EventArgs e)
{
LinkButton editButton = (LinkButton) sender;
int index = Convert.ToInt32(editButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton updateButton = (LinkButton)row.FindControl("updateButton");
updateButton.Visible = true;
editButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
checkbox.Enabled = true;
// Get value and update
}
}
protected void updateButton_Click(object sender, EventArgs e)
{
LinkButton updateButton = (LinkButton)sender;
int index = Convert.ToInt32(updateButton.CommandArgument);
GridViewRow row = gridView.Rows[index];
// Get the PlaceHolder control
LinkButton editButton = (LinkButton)row.FindControl("updateButton");
editButton.Visible = true;
updateButton.Visible = false;
CheckBox checkbox = (CheckBox)row.FindControl("auCheckBox");
if (checkbox != null)
{
// Get value and update
checkbox.Enabled = false;
}
}
If you want to be it enabled from the get go, just remove the enabled checks and you can delete your edit button.
Hope that helps.

How can I get the selected value from dropdownlist in edit mode of a gridview?

In my application, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList emailsListDL = (DropDownList)e.Row.FindControl("emailsDL");
emailsListDL.DataSource = allUsersEmails;//list of strings with the emails of the users
emailsListDL.DataBind();
}
}
}
But when I press the 'Update' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList emailsListDL = (DropDownList)GridViewAdvertisers.Rows[e.RowIndex].FindControl("emailsDL");
string email = emailsListDL.SelectedValue; //the selected value is every time the first value from the dropdownlist
}
Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck. I tried this:
1. emailsListDL.SelectedIndex = emailsListDL.Items.IndexOf(emailsListDL.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "OwnerMail").ToString()));
2. emailsListDL.SelectedValue = GridViewAdvertisers.DataKeys[e.Row.RowIndex]["OwnerMail"].ToString();
3. emailsListDL.SelectedValue = GridViewAdvertisers.Rows[e.Row.RowIndex].Cells[1].Text;
//ownerMail is a string (object) from the list of objects that I put as datasource to the gridview
Thanks,
Jeff
Update
My Item template from the aspx page is:
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="150px" HeaderText="Owner Email" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<asp:Label ID="LabelEmail" runat="server" Text='<%# Bind("OwnerMail")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="emailsDL" runat="server" Width="150">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="180px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
The SelectedIndex will always default to 0 if you don't define it in your DropDownList definition.
Edit: #Tim Schmelter should add his comment as an anwer. In the meantime, I'll paraphrase for other readers: You need to check for postback (see comments above).
You can declare a ComboBox mainBX = new Combobox();
and you can declare an event
private void onSeletedIndexChange(object sender,EventArgs e)
{
mainBX = (ComboBox)(sender);
}
and next you should iterate foreach ComboBox in GridView and Add this Event .
Than all you should do is ,take the mainBX.seletedItem();
I think this is what you need ,if not apologise .
To set the Selected Value in the RowDataBound-Event, you should do it like this:
(DropDownList)e.Row.Cells[/*index*/].Controls[/*index, or use FindControl*/]).Items.FindByValue(((DataRowView)e.Row.DataItem).Row.ItemArray[/*columnnumber*/].ToString()).Selected = true;
FindByValue finds the current Textvalue of the Field in the "normal" Viewmode and sets the DropDownList with the value.
Of course this needs to be encapsulated in
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
}
As for your "getting the Value at Update"-Problem, I must honestly say I've got no clue, since your approach is exactly like mine, only difference: mine works.
Here's my code if it's any help:
protected void gridVariables_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string control = ((DropDownList)gridVariables.Rows[e.RowIndex].Cells[3].Controls[1]).SelectedValue;
gridVariables.EditIndex = -1;
this.gridVariables_DataBind(control, e.RowIndex);
}
private void gridVariables_DataBind(string control, int index)
{
DataTable dt = (DataTable)Session["variableTable"]; //features a DataTable with the Contents of the Gridview
dt.Rows[index]["ControlType"] = control;
gridVariables.DataSource = dt;
gridVariables.DataBind();
}
I had the same problem with a different solution, I had implemented custom paging on the GridView with a custom pager, and in the process added the RowCommand method, which was rebinding the grid with a new page index. As it happens though the RowCommand method is also called during Updating.
So be sure to check any other locations you may be binding anywhere in your code.
Hope this helps somebody else.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string commandName = e.CommandName;
switch (commandName)
{
case "Page1":
HandlePageCommand(e);
//binding should happen here
break;
}
//this line is in the wrong location, causing the bug
BindGrid1();
}

Categories