accessing gridview hiddenfield - c#

' />
I want to access the value in the hidden field in my code behind. I know i need to do this when the item is bound but i cant seem to work out how to do it.
protected void addLabelsWhereNeeded(object sender, EventArgs e)
{
// Get Value from hiddenfield
}

Try adding
OnRowDataBound="addLabelsWhereNeeded"
to your GridView. Then cast the control in the corresponding cell to a HiddenField to grab the value:
protected void addLabelsWhereNeeded(object sender, GridViewRowEventArgs e)
{
HiddenField hf = e.Row.Cells[0].Controls[1] as HiddenField;
String theValue = hf.Value;
}
assuming you've defined your GridView as:
<asp:GridView runat="server" ID="gv" OnRowDataBound="addLabelsWhereNeeded">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--your hidden field--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Just make sure you are indexing the correct cell and correct control within that cell.

yes you are right. You must do it on ItemDateBound. Check It must work

I do quite see what you want to achieve with this private field while databinding? In the RowDataBound Event you can access the whole data item, so there is no need for the use of a hidden value.
Pseudocode:
protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs)
{
if(e.RowType == RowType.DataRow)
{
}
}
Set a Breakpoint into if clause and use quickwatch to see how you need to cast the DataItem that is currently bound to gain full access to all properties, even if they aren't bound to any control.

Related

asp.net: How to update data in GridView through Checkbox in particular row

I am developing a Web Form, where I show Gridview with data. One of the column consists of CheckBox. How can I update data in particular row.
so my question is:
How to unidentified particular row and send an sql request with UPDATE when user Check or Uncheck the CheckBox?
Update:
Here is my code that i have. It doesn't update value of CheckBox.
namespace:
public partial class Call_Bills : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
string check;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button_Submit(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView2.Rows)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["TestDeductionsConnectionString2"].ToString();
con.Open();
bool private1 = (row.FindControl("CheckBox1") as CheckBox).Checked;
if (private1 == true)
{
check = "1";
}
else
{
check = "0";
}
SqlCommand cmd = new SqlCommand("insert into DetailCosts(private) values(#private)", con);
cmd.Parameters.AddWithValue("#private", check);
cmd.ExecuteNonQuery();
}}
name of GridView is: GridView2;
name of Checkbox in the Table: private;
id of CheckBox in Gridview is:
<asp:TemplateField HeaderText="Private" SortExpression="private">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("private") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
you can manually define a method to handle a postback generated by a control inside a gridview column. To do that you just need to add the tags AutoPostBack=True and OnCheckedChanged=YourMethodName to the control.
On the code-behind, define this method as public void, and define the parameters that usually would be there (sender as object and e as EventArgs), like:
public void YourMethodName(object sender, EventArgs e)
On the method, you may need to get the GridViewRow which contains the control that has generated the event. To do that, just parse the sender parameter (which will be the checkbox) and get 2 parent levels (GridViewCell and GridViewRow), it would be something like:
GridViewRow row = ((CheckBox)sender).parent.parent;
Since you have the row, you may get any control inside it with the FindControl method. If you need an id to identify the entitiy being updated, you may store it in a hidden field inside the row.
Hope it helps!

Can't update using FindControl

I have a TextBox within my EditItemTemplate in my listview_car:
<EditItemTemplate>
<asp:TextBox ID="txt1" runat="server" Text='<%# Bind("photo1") %>' Visibile="true">
</asp:TextBox>
</EditItemTemplate>
Now in the code I have this in my ItemUpdating event:
protected void listview_car_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
var txt1 = listview_car.Items[0].FindControl("txt1") as TextBox;
txt1.Text = "newImage";
}
Now I have debugged it and the value that is showing from my DB is correct, then when I set it from the code using txt1.Text = "newImage"; it shows it has updated the textbox in the Auto's however it does not update in the DB, but the strange thing is when I type in the textbox and click the edit button it updates but doesn't update when I set the string in the code?
Does anyone know what I am doing wrong?
When ItemUpdating() is called all values were already collected in the NewValues collection. To modify any of values you should modify e.NewValues
protected void listview_car_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
e.NewValues["key"] = "newImage";
}
where "key" is a name of the key (not a name of the control) which is usually a column name. You could also use an index 0,1,2...
In listview_car_ItemUpdating, first update the database, then call whatever method you used to bind your controls to the database when the page first loaded. This will retrieve the new value of photo1 from the database and bind it to txt1.

Bind a list of users controls to gridview

I desperately seeks in vain. I want to bind a List(T) of Users Controls (.ascx) to a gridview. I initialize my controls in code-behind :
List<myControl> ctrls = new List<myControl>();
myControl ctr = LoadControl("~/Control.ascx") as myControl;
ctr.Name = ...
// ...
ctrls.Add(myControl); // add new control to the collection
And after, i bind this list to Gridview control :
this.GridView1.DataSource = ctrls;
this.gridView1.DataBind();
In the Page_Load event with condition If (!IsPostBack). This does not work: the representation of the object is displayed. Whereas when I put the controls in a Panel, all worked.
Don't use a GridView for this. Use a Repeater. And bind it to the data, not to list of controls. Example:
<asp:Repeater runat="server" id="ControlsRepeater">
<ItemTemplate>
<uc:MyControl runat="server" />
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var myData=GetData(); //should return some type of ICollection representing your data to bind to
ControlsRepeater.DataSource=myData;
ControlsRepeater.DataBind();
}
}
If you want paging, then you should take advantage of lazy loading (the Entity Framework handles this for you if you use that) and the Linq functions .Take() and .Skip().

Obtaining value of Textbox contained within DataList: Where did I go wrong?

I'm attempting to set the parameter of an insert command equal to the value of a text box contained within a DataList control.# The following is my attempt at finding the relevant control and retrieving its value.
protected void SqlDataSource1_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
TextBox Amt = (TextBox)DataList1.Items[0].FindControl("RadTextBox1");
e.Command.Parameters["#Amount"].Value = Convert.ToDecimal(Amt.Text);
}
The above code sample does not work but also does not return any syntax errors. I suspect I did something wrong in trying to get the textbox value because the insert statement works fine if I set the #Amount parameter equal to some arbitrary value. Can someone please show me my mistake and how to correct it?
//Additional code per comment
DataList:
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"><ItemTemplate>
<telerik:RadTextBox ID="RadTextBox1" runat="server" Text='<%# Eval("TotalProratedAmountDue") %>'>
</telerik:RadTextBox>
</ItemTemplate>
</asp:DataList>
Insert Button:
public void RadButton2_Click(object sender, EventArgs e)
{
SqlDataSource1.Insert();
}
Perhaps because you're looking for RadTextBox1 but the ID is RadTextBox2?
If Amt.Text returns a NULL, then Convert.ToDecimal(Amt.Text) will return a 0. But I'm not sure what you mean by "the above example does not work". You mean no records get inserted?
Well to start - your code references RadTextBox1 yet in your markup its RadTextBox2

How to hide a column (GridView) but still access its value?

I have a GridView with a DataSource (SQL Database). I want to hide a column, but still be able to access the value when I select the record. Can someone show me how to do this?
This is the column I want to hide and still want to access its value:
<asp:BoundField DataField="Outlook_ID" HeaderText="OutlookID" />
I tried everything to hide the column (property Visible="false"), but I can't access its value.
<head runat="server">
<title>Accessing GridView Hidden Column value </title>
<style type="text/css">
.hiddencol
{
display: none;
}
</style>
<asp:BoundField HeaderText="Email ID" DataField="EmailId" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" >
</asp:BoundField>
ArrayList EmailList = new ArrayList();
foreach (GridViewRow itemrow in gvEmployeeDetails.Rows)
{
EmailList.Add(itemrow.Cells[YourIndex].Text);
}
If I am not mistaken, GridView does not hold the values of BoundColumns that have the attribute visible="false". Two things you may do here, one (as explained in the answer from V4Vendetta) to use Datakeys. Or you can change your BoundColumn to a TemplateField. And in the ItemTemplate, add a control like Label, make its visibility false and give your value to that Label.
Define a style in css:
.hiddencol { display: none; }
Then add the ItemStyle-CssClass="hiddencol" and the HeaderStyle-CssClass="hiddencol" attribute to the grid field:
<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" ClientIDMode="Static" />
You can use DataKeys for retrieving the value of such fields, because (as you said) when you set a normal BoundField as visible false you cannot get their value.
In the .aspx file set the GridView property
DataKeyNames = "Outlook_ID"
Now, in an event handler you can access the value of this key like so:
grid.DataKeys[rowIndex]["Outlook_ID"]
This will give you the id at the specified rowindex of the grid.
You can do it programmatically:
grid0.Columns[0].Visible = true;
grid0.DataSource = dt;
grid0.DataBind();
grid0.Columns[0].Visible = false;
In this way you set the column to visible before databinding, so the column is generated.
The you set the column to not visible, so it is not displayed.
If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:
<asp:TemplateField HeaderText="OutlookID">
<ItemTemplate>
<asp:Label ID="blah" runat="server">Existing Control</asp:Label>
<asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:
string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;
Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.
You can make the column hidden on the server side and for some reason this is different to doing it the aspx code. It can still be referenced as if it was visible. Just add this code to your OnDataBound event.
protected void gvSearchResults_DataBound(object sender, EventArgs e)
{
GridView gridView = (GridView)sender;
if (gridView.HeaderRow != null && gridView.HeaderRow.Cells.Count > 0)
{
gridView.HeaderRow.Cells[UserIdColumnIndex].Visible = false;
}
foreach (GridViewRow row in gvSearchResults.Rows)
{
row.Cells[UserIdColumnIndex].Visible = false;
}
}
Leave visible columns before filling the GridView. Fill the GridView and then hide the columns.
Here is how to get the value of a hidden column in a GridView that is set to Visible=False: add the data field in this case SpecialInstructions to the DataKeyNames property of the bound GridView , and access it this way.
txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")
That's it, it works every time very simple.
I have a new solution hide the column on client side using css or javascript or jquery.
.col0
{
display: none !important;
}
And in the aspx file where you add the column you should specify the CSS properties:
<asp:BoundField HeaderText="Address Key" DataField="Address_Id" ItemStyle-CssClass="col0" HeaderStyle-CssClass="col0" > </asp:BoundField>
I used a method similar to user496892:
SPBoundField hiddenField = new SPBoundField();
hiddenField.HeaderText = "Header";
hiddenField.DataField = "DataFieldName";
grid.Columns.Add(hiddenField);
grid.DataSource = myDataSource;
grid.DataBind();
hiddenField.Visible = false;
I found this solution, an elegant(IMO) quick 2 parter.
1.
On your gridview, add a column as normal, no need to do anything differently:
<asp:BoundField DataField="AccountHolderName" HeaderText="Account Holder"
ReadOnly="true"/>
You can keep the header text if this is useful to you for later processing.
2.
In the rowdatabound method for the grid hide the header, footer and row for that column index:
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[10].Visible = false;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[10].Visible = false;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[10].Visible = false;
}
You can do it code behind.
Set visible= false for columns after data binding .
After that you can again do visibility "true" in row_selection function from grid view .It will work!!
I searched a lot but no luck. The most of them was working with some errors. Finally I used this code and it worked for me.
probably you should change 1 to some other value. for me I would hide second col.
protected void FoundedDrGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType!=DataControlRowType.Pager)e.Row.Cells[1].Visible = false;
}
I just set the width to 0. and it works.
columns.AddFor(m => m.Id).Name("hide-id").Width(0);
When I want access some value from GridView before GridView was appears.
I have a BoundField and bind DataField nomally.
In RowDataBound event, I do some process in that event.
Before GridView was appears I write this:
protected void GridviewLecturer_PreRender(object sender, EventArgs e)
{
GridviewLecturer.Columns[0].Visible = false;
}

Categories

Resources