Can't update using FindControl - c#

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.

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!

get value on edititemtemplate from codebehind

I have a detailsview where I get couple of data from membership profile and I display it on detailsview...this works fine:
<ItemTemplate>
<asp:label ID="FirstName" runat="server" />
</ItemTemplate>
But when I click the edit button, nothing shows up on the field. This is what I am doing on Edit template:
I call ItemUpdating like this:
protected void DetailsView1_ItemUpdating(Object sender, DetailsViewUpdateEventArgs e)
{
//I get my memberprofle here
MemberProfile memberp = MemberProfile.GetuserProfile(data);
MembershipUser myuser = Membership.GetUser()
Label labelfName = DetailsView1.FindControl("FirstName") as Label;
labelfName.Text = memberp.fName;
}
Should I be using Itemupdated instead? Or is there another method that I should call when the edit button is clicked that will populate the firstname field on edit? Also, the reason I am keeping it as "LABEL"(usually it would be textbox) on edit mode is that this field has to be read only.
The event ItemUpdating is not fired when you enter on edit mode. You must use DataBound event to set properly required text value.
If neccesary, you can ask CurrentMode property of DetailsView to know if you are editing or displaying.
The result looks like this:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
Label l = DetailsView1.FindControl("FirstName") as Label;
if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
{
//obtained from your sample
MemberProfile memberp = MemberProfile.GetuserProfile(data);
MembershipUser myuser = Membership.GetUser()
l.Text = memberp.fName;
}
else
{
l.Text = "Another text or nothing";
}
}
Be sure to define DataBound event in you Detailsview1 control.
REMARK: It can be affected depending the data bind mode. If so, let me know and put an example.
Add RowUpdating and RowEditing event to your gridview.
http://www.aspdotnet-suresh.com/2011/02/how-to-inserteditupdate-and-delete-data.html

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

accessing gridview hiddenfield

' />
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.

reset selectedvalue when textbox change

I have a textbox and a dropdownlist
the textbox has
<asp:TextBox ID="TxtInizioPeriodo" runat="server"
ontextchanged="InizioPeriodo_TextChanged" AutoPostBack="true" Width="100"></asp:TextBox>
i want if it changes the dropdownlist return to default value selected
i try to pur in page load this:
SelectDestinazione[i].SelectedValue = "";
but it now works.
how can i do?
thanks
In your code you have mentioned like
Array of Dropdownlist ie.,
SelectDestinazione[i].SelectedValue = "";
in the above code "i" selects dropdownlist object from the array of dropdownlists.
Kindly check that one. If its is the single dropdownlist box then use the below solution.
Copy & paste the below code in the server side during the text content change event.
protected void InizioPeriodo_TextChanged(object sender, EventArgs e)
{
SelectDestinazione.SelectedIndex = -1;
}
I assume SelectDestinazione is your dropdownlist
SelectDestinazione.clearSelection();

Categories

Resources