I'm trying to get the value from the selected item when I click a button.
Here is my code:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<p class="own"><asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImageDatafromDB.aspx?id=" + System.Convert.ToString(Eval("ID")) %>' Width="230" Height="250"/>
<br />
<span class="own1" style="width:230px;"><br /><asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="White"/>
<br />
<asp:Label ID="Label5" runat="server" Text="Direktor :" style="color:#06D85F; float:left"></asp:Label><asp:Label ID="Label2" runat="server" CssClass="InFo" Text='<%# Eval("fattare") %>' Font-Italic="true"/>
<br />
<asp:Label ID="Label4" runat="server" Text="Year : " style="color:#06D85F; float:left;"></asp:Label><asp:Label ID="Label3" CssClass="InFo" runat="server" Text=' <%# (Eval("Ar")) %>' />
</br>
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
</span>
<asp:Label ID="Label6" runat="server" Visible="false" Text='<%# Eval("Name") %>'></asp:Label>
</p>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["Hemsida"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Movies", conn);
ad.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Label myTempLabel = (Label)item.FindControl("Label6");
myTempLabel.Visible = true;
}
}
When I click the button, I get all of the names of all of the items, but I only want to get the name of the selected item.
On the ItemCommand event of DataList1, paste the following code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList1.SelectedIndex = e.Item.ItemIndex;
myTempLabel.Text = "You selected: " + ((Label)DataList1.SelectedItem.FindControl("Label1")).Text;
myTempLabel.Visible = true;
}
I believe you need to use SelectedItem.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.selecteditem(v=vs.110).aspx
Something like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (DataList1.SelectedItem != null)
{
Label myTempLabel = (Label)DataList1.SelectedItem.FindControl("Label6");
myTempLabel.Visible = true;
}
}
Try changing this:
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
to This:
<asp:Button ID="Button1" runat="server" Text="Visa" OnClick="Button1_Click"
/>
Another alternative is to remove the code in the button and handle it on the Item_Command:
//Add item command to DataList
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" OnItemCommand="Item_Command">
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
//Get the selected Item
DataListItem selectedItem = DataList1.DataKeys[DataListList1.SelectedIndex];
//Get the label control
Label myTempLabel = (Label)selectedItem.FindControl("Label6");
myTempLabel.Visible = true;
// Not sure if this is needed.
//ItemsList.DataSource = CreateDataSource();
//ItemsList.DataBind();
}
If the textbox that gets the value is outside your update panel then try this:
if (e.CommandName == "selectitem")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
TextBox2.Text = Label)DataList1.SelectedItem.FindControl("Label1")).Text;
}
If the textbox that gets the value is inside your update panel then try this
if (e.CommandName == "selectitem")
((Label)e.Item.FindControl("Label1")).Text = e.CommandArgument.ToString();
Related
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.
I've got a tab control with a gridview in it. I want to add new records using the footer row but when I try and save the record, I can't find the value in the textbox. I've set the clientidmode = static, I've also tried using a recursive findcontrol but to no avail. Please can someone help
Thanks
<asp:UpdatePanel ID="pnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TabContainer ID="TabDetails" runat="server" AutoPostBack="true" OnActiveTabChanged="TabDetails_ActiveTabChanged"
ActiveTabIndex="1">
<asp:TabPanel runat="server" ID="TabNotes" HeaderText="Notes" CssClass="tabinactive">
<ContentTemplate>
<asp:GridView ID="GrdNotes" ClientIDMode="Static" runat="server" AutoGenerateColumns="false"
Width="99%" OnRowEditing="GrdNotes_RowEditing" OnRowCancelingEdit="GrdNotes_RowCancelingEdit"
OnRowUpdating="GrdNotes_RowUpdating" OnRowDeleting="GrdNotes_RowDeleting" OnRowCreated="GrdNotes_RowCreated"
ShowFooter="false">
<Columns>
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:HiddenField ID="hfNotesID" runat="server" Value='<%# Bind("Notes_ID")%>' />
<asp:Label ID="LblNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtNewNotes" ClientIDMode="Static" runat="server" Width="300px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Notes_Date" ReadOnly="True" DataFormatString="{0:dd/MM/yyyy}"
HeaderText="Date" />
<asp:BoundField DataField="FullName" ReadOnly="True" HeaderText="Entered By" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add Notes" OnClick="btnAddVisitNotes_Click" />
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
private void BindNotes(int id)
{
var qry = from vn in dc.sp_list_notes(id)
orderby vn.Notes_Date descending
select vn;
GrdNotes.DataSource = qry.ToList();
GrdNotes.DataBind();
}
protected void GrdNotes_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var lnk = new LinkButton();
lnk.Text = "Save";
lnk.ID = "btnAddNotesSave";
lnk.CausesValidation = false;
lnk.Command += new CommandEventHandler(btnAddNotesSave_Click);
lnk.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk);
var lbl = new Label();
lbl.Text = "XX";
lbl.ID = "LblSpace";
lbl.CssClass = "norm_w";
e.Row.Cells[1].Controls.Add(lbl);
var lnk1 = new LinkButton();
lnk1.Text = "Cancel";
lnk1.ID = "btnAddNotesCancel";
lnk1.CausesValidation = false;
lnk1.Command += new CommandEventHandler(btnAddNotesCancel_Click);
lnk1.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk1);
}
protected void btnAddNotes_Click(object sender, EventArgs e)
{
GrdNotes.ShowFooter = true;
BindNotes(int.Parse(hfID.Value));
}
protected void btnAddNotesSave_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)GrdNotes.FooterRow.FindControl("TxtNewNotes") ;
string sNotes = txt.Text;
}
"Can't find the value in the textbox" means that you can find the TextBox via FindControl but it's Text property returns String.Empty?
There is definitely text in the textbox, but it's returning "". if I
do a check txt.id it returns "TxtNewNotes" but txt.text = ""
Maybe you have forgotten to add a !IsPostBack check before you call BindNotes in Page_Load.
Thank you, yes I can't believe I forgot that!
Even the most experienced ASP.NET developers sometimes forget this ;)
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
BindNotes();
}
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();
}
As i was written in the title, the problem is very funny :
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id_Newsletter" HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White" RowStyle-BackColor="DarkGray" AlternatingRowStyle-BackColor="LightGray" PageSize="6" AllowPaging="true"
AllowSorting="true" ShowHeaderWhenEmpty="true" EmptyDataText="La tabella non contiene dati" EnableViewState="true" RowStyle-Wrap="true"
PagerStyle-HorizontalAlign="Left" PagerStyle-BorderWidth="0" BorderWidth="0" OnRowCommand="GridView_RowCommand"
OnRowCancelingEdit="GridView_RowCancelingEdit" OnRowUpdating="GridView_RowUpdating" OnRowDeleting="GridView_RowDeleting"
OnPageIndexChanging="GridView_PageIndexChanging" OnSorting="GridView_Sorting" OnRowEditing="GridView_RowEditing" CssClass="NewsletterManager_GridView" >
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Indirizzo Email" HeaderStyle-Width="275" SortExpression="emailNewsletter">
<ItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>' Visible="false" ></asp:Label>
<asp:TextBox ID="txt_emailNewsletter" runat="server" Text='<%# Bind("emailNewsletter") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Azioni" HeaderStyle-Width="100">
<EditItemTemplate>
<asp:ImageButton ID="Img_Aggiorna" runat="server" CommandName="Update" ImageUrl="~/images/GridIcon/update.png" ToolTip="Aggiorna" />
<asp:ImageButton ID="Img_Annulla" runat="server" CommandName="Cancel" ImageUrl="~/images/GridIcon/undo.png" ToolTip="Annulla" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="Img_Modifica" runat="server" CommandName="Edit" ImageUrl="~/images/GridIcon/edit.png" ToolTip="Modifica" />
<asp:ImageButton ID="Img_Cancella" runat="server" CommandName="Delete" ImageUrl="~/images/GridIcon/delete.png" OnClientClick="return confirm('Sei sicuro di voler cancellare l\'email?');" ToolTip="cancella" />
</ItemTemplate>
</asp:TemplateField>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
LoadGridView(GridView1, -1, 0);
lbl_result.Text = String.Empty;
}
protected void GridView_RowEditing(Object sender, GridViewEditEventArgs e)
{
LoadGridView(((GridView)sender), e.NewEditIndex, ((GridView)sender).PageIndex);
}
protected void GridView_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
NewsLetterBL newsBl = new NewsLetterBL();
String oldmail = ((Label)((GridView)sender).Rows[e.RowIndex].FindControl("lbl_emailNewsletter")).Text;
String newmail = ((TextBox)((GridView)sender).Rows[e.RowIndex].FindControl("txt_emailNewsletter")).Text;
if (newsBl.ModifyWrongEmail(oldmail, newmail))
lbl_result.Text = "Modify Done";
else lbl_result.Text = newsBl.LastMessage;
LoadGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
}
protected void LoadGridView(GridView GV, int EditIndex, int PageIndex)
{
NewsLetterBL newsBl = new NewsLetterBL();
DataView dw = new DataView(newsBl.getFullNewsletter());
String SortExpression = GV.ID.ToString() + "_SortExpression";
if (ViewState[SortExpression] != null) dw.Sort = (String)ViewState[SortExpression];
GV.DataSource = dw;
GV.PageIndex = PageIndex;
GV.EditIndex = EditIndex;
GV.DataBind();
}
When I try to access to the txt_emailNewsletter control into the row in edit mode from the GridView_RowUpdating that handle the OnRowUpdating event of the GridView1, the element throws a NullReferenceException, but the lbl_emailNewsletter control can be founded.
The labels into ItemTemplate and EditItemTemplate have the same ID (lbl_emailNewsletter): if I change the ID of the label into the ItemTemplate, both the String oldmail and newmail throws an exception of null Reference ; clearly the problem is that when I click on ImageButton Img_Aggiorna with CommandName="Update", ASP.NET for a mysterious reason Find only controls of ItemTemplate instead of EditItemTemplate from the edited row.
GridView event "OnRowUpdating" is useful only if you use a datasource : in this case is possible to access to the Dictionary e.OldValues[] or e.NewValues[] and get correctly the old and new values.
I have solved the problem using the event "OnRowCommand" with a personalized CommandName and a CommandArgument with the old values : in this case is possible to access to all the controls inside the edited row in the GridView with the new values.
<asp:ImageButton ID="Img_Update" runat="server" CommandName="Change" CommandArgument='<%# Eval("emailNewsletter") %>' ImageUrl="~/images/GridIcon/update.png" ToolTip="Update" />
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Change":
ImageButton btnNew = e.CommandSource as ImageButton;
GridViewRow row = btnNew.NamingContainer as GridViewRow;
TextBox txt_emailNewsletter = row.FindControl("txt_emailNewsletter") as TextBox;
if ( !CheckEmail(e.CommandArgument.ToString()) || !CheckEmail(txt_emailNewsletter.Text) )
lbl_result.Text = "ERROR : Email not Valid";
else {
if (txt_emailNewsletter.Text.Trim().ToLower() == e.CommandArgument.ToString())
lbl_result.Text = "Email values are indentical";
else
{
//Business Layer Call
NewsLetterBL newsBl2 = new NewsLetterBL();
if (newsBl2.ModifyWrongEmail(e.CommandArgument.ToString(), txt_emailNewsletter.Text.Trim().ToLower()))
lbl_result.Text = "Email Changed";
else
lbl_result.Text = "ERROR : " + newsBl2.LastMessage;
}
}
LoadDataForGridView(((GridView)sender));
BindGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
break;
}
}
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
}
}