I have searched about this topic all over the internet and have come up with nothing. Either I am having a hardtime wording my problem or I am do something so wrong that no one else has ever even tried it...
I have a gridview. I am using a button in the gridview to execute a command to open a ModalPopupExtender. That part works great. Once I have the popup open, I want to be able to press a button to execute a function which will perform a Sql query and bind a gridview that is INSIDE the popup panel. After that the user can perform an action with the gridview which would close the modal popup.
Here is my HTML -
<cc1:ModalPopupExtender runat="server" ID="MPE_Issue" PopupControlID="pnlIssue" BackgroundCssClass="ModalPopupBG"
TargetControlID="Hid_Sno" CancelControlID="btnIssueCancel">
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlIssue" runat="server" Style="display: none" >
<div class="HelloPopup">
<div>
<br />
<h2> Issue Equipment</h2>
<br />
<asp:Panel runat="server" ID="pnlIssueSearch" DefaultButton="btnIssueSearch">
<div class="block" style="text-align: right; margin-left: 50px">
<asp:Label CssClass="lblBlock" runat="server" ID="lblIssueSearch" Text="Search:"></asp:Label>
</div>
<div class="block">
<asp:TextBox runat="server" ID="txtIssueSearch" Width="160px"></asp:TextBox>
<asp:ImageButton runat="server" ID="btnIssueSearch" ImageUrl="../Images/search.png" OnClick="btnIssueSearch_Click" />
</div>
</asp:Panel>
<asp:Panel runat="server" ID="pnlIssueSubmit" DefaultButton="btnIssueSubmit">
<div style="width: 275px; margin: auto; height: 295px; overflow: scroll;">
<asp:GridView runat="server" ID="gvIssue" AutoGenerateColumns="false" CssClass="mGrid" OnRowCommand="gvIssue_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtIssueQty" runat="server" Text='<%# Bind("QTY") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Assignment" DataField="FIRST_NAME" />
</Columns>
</asp:GridView>
</div>
<div class="center">
<asp:Button runat="server" ID="btnIssueSubmit" Text="Issue" OnClick="btnIssueSubmit_Click" />
<input type="button" id="btnIssueCancel" value="Cancel" />
</div>
</asp:Panel>
And the codebehind -
protected void gv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "issue")
{
GridViewRow gvr3 = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
string itemNo = ((Label)gvr3.Cells[0].FindControl("lblItemNo")).Text;
btnIssueSubmit.Visible = false;
txtIssueSearch.Text = "";
MPE_Issue.Show();
}
protected void btnIssueSearch_Click(object sender, ImageClickEventArgs e)
{
string query = "SELECT QTY, NEW_EMP_ID as NAME FROM TRANSACTION_TRACKING WHERE NEW_EMP_ID = #inputINT";
string inputString = "%" + txtIssueSearch.Text + "%";
int inputINT = Convert.ToInt32(txtIssueSearch.Text);
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter(query, con);
SqlParameter parameter = new SqlParameter("inputString", inputString);
SqlParameter parameter2 = new SqlParameter("inputINT", inputINT);
da.SelectCommand.Parameters.Add(parameter);
da.SelectCommand.Parameters.Add(parameter2);
DataSet ds = new DataSet();
da.Fill(ds);
gvIssue.DataSource = ds;
gvIssue.DataBind();
btnIssueSubmit.Visible = true;
MPE_Issue.Show();
}
EDIT/SOLUTION
I was going about solving this problem wrong. I wanted to override the nature of asp.net instead of going with the flow and solving the problem systematically. To overcome this issue I changed my data bind into its own method and had the button within the panel activate the that method, set the popup control to Open(), and also set a boolean from false to true. Then on the page_load I have an event that checks the boolean and automatically does the data Method if it is true (and therefore a search parameter is in the textbox).
Thanks all for the suggestions and help.
If you make your pnlIssueSubmit an UpdatePanel then do an asyncpostback trigger on btnIssueSearch wouldn't that fix your issue? Because your imageButton needs to do a post back in order to refresh you grid but then you'll lose your modal. Something like this:
<asp:UpdatePanel id="pnlIssueUpdate" runat="server">
<ContentTemplate>
<asp:Panel runat="server" ID="pnlIssueSubmit" DefaultButton="btnIssueSubmit">
<div style="width: 275px; margin: auto; height: 295px; overflow: scroll;">
<asp:GridView runat="server" ID="gvIssue" AutoGenerateColumns="false" CssClass="mGrid" OnRowCommand="gvIssue_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="txtIssueQty" runat="server" Text='<%# Bind("QTY") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Assignment" DataField="FIRST_NAME" />
</Columns>
</asp:GridView>
</div>
<div class="center">
<asp:Button runat="server" ID="btnIssueSubmit" Text="Issue" OnClick="btnIssueSubmit_Click" />
<input type="button" id="btnIssueCancel" value="Cancel" />
</div>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:asyncPostBackTrigger ControlID="btnIssueSearch" />
</Triggers>
I was going about solving this problem wrong. I wanted to override the nature of asp.net instead of going with the flow and solving the problem systematically. To overcome this issue I changed my data bind into its own method and had the button within the panel activate the that method, set the popup control to Open(), and also set a boolean from false to true. Then on the page_load I have an event that checks the boolean and automatically does the data Method if it is true (and therefore a search parameter is in the textbox).
Related
i will try to explain what i have, what i'm trying to do and what is my problem
what i have:
i have a modal with and update panel (i need it because the postback closes my modal) that has two text box, a button and a gridview.
in the textbox i write the name and the surname of a person and with the button i retrieve the data and put it in a gridview.
the gridview has a control to select the row that i want, with that row, i use the data from first three cells to change some hidenField values to use in another function.
in the bottom of the modal i have the add button that only changes a textbox to show that i have the correct data. that button is not enabled by default and the event must enable it
what i want:
i want to select the row that i need, enable the add button and fetch the data in my textbox.
where is my problem:
when i select my row, selectedindexchanging fires but nevers enables the add button so cant fetch my textbox for using it
code:
front code:
<div class="modal fade" id="modalSocio" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabelSocio">
<asp:Label ID="Label4" runat="server" CssClass="text-primary"></asp:Label>
</h5>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div class="modal-body">
<div class="row g-3">
<div class="row">
<div class="col-3">
<asp:TextBox ID="txtBusquedaNombre" runat="server" CssClass="form-control" placeholder="Nombre"></asp:TextBox>
</div>
<div class="col-3">
<asp:TextBox ID="txtBusquedaApellido" runat="server" CssClass="form-control" placeholder="Apellido"></asp:TextBox>
</div>
<div class="col-3">
<asp:LinkButton ID="btnBuscarSocio" runat="server" CssClass="btn btn-outline-success" Text="Buscar" CausesValidation="false" ToolTip="Buscar" OnClick="btnBuscarSocio_Click" ><span class="fas fa-search"></span></asp:LinkButton>
</div>
</div>
<div class="table-responsive mt-3">
<asp:GridView ID="gvSocios" runat="server" CssClass="table table-bordered" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnSelectedIndexChanging="gvSocios_SelectedIndexChanging" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Legajo" HeaderText="Nro. Socio" ></asp:BoundField>
<asp:BoundField DataField="nombreSocio" HeaderText="Nombre" />
<asp:BoundField DataField="Apellido" HeaderText="Apellido" />
<asp:CommandField ButtonType="Link" HeaderText="Seleccionar" ShowSelectButton="True" SelectText="<i class='fa fa-check-circle'></i>">
<ControlStyle CssClass="btn btn-outline-secondary" />
</asp:CommandField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
<EmptyDataTemplate>
<div class="alert alert-primary" role="alert">
No se encontraron registros!
</div>
</EmptyDataTemplate>
</asp:GridView>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div class="modal-footer">
<asp:Button ID="BtnCancelarSocio" runat="server" Text="Cancelar" CssClass="btn btn-secondary" OnClick="btnCancelar_Click" CausesValidation="False" />
<asp:Button ID="BtnAgregarSocio" ClientIDMode="Static" runat="server" CausesValidation="false" Text="Seleccionar" CssClass="btn btn-success" OnClick="BtnAgregarSocio_Click" />
</div>
</div>
</div>
</div>
codeBehind:
protected void BtnAgregarSocio_Click(object sender, EventArgs e)
{
TxtSocio.Text = hfidNombreSocio.Value;
}
protected void gvSocios_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
var row = gvFormasPago.Rows[e.NewSelectedIndex];
BtnAgregarSocio.Enabled = true;
hfSocio.Value = row.Cells[0].Text;
hfidNombreSocio.Value = row.Cells[0].Text + " - " + row.Cells[1].Text + " " + row.Cells[2].Text;
}
i tried to not use the enabled attribute for test but when the click event fires the hfidNombreSocio value in that moment is empty and the modal never closes.
maybe i'm not using the update panel right.
the text box code:
<div class="row">
<div class="col-md-4">
<asp:Label ID="lblSocio" runat="server" Visible="false" Text="Socio Cuenta Corriente" CssClass="form-label"></asp:Label>
<asp:TextBox ID="TxtSocio" runat="server" text="0" CssClass="form-control" ></asp:TextBox>
<asp:LinkButton ID="btnBuscar" runat="server" Visible="false" CssClass="btn btn-outline-success" Text="Buscar" CausesValidation="false" ToolTip="Buscar" OnClick="btnBuscar_Click" ><span class="fas fa-search"></span></asp:LinkButton> <%-- this button open the modal --%>
</div>
Ok, folks, this is one of those I wish someone corrected me!!
I am MOST HAPPY to have big buckets of egg on my face.
I have for some time preached that when you pop a dialog, you can't have post backs in that dialog. I stand MUCH corrected!!!!
So, lets build a grid, it allows a search, and then we can click on (select the row).
We have this:
<div id="hoteldialog1" style="display:normal">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Enter City Name: <asp:TextBox ID="txtSearchCity" runat="server"></asp:TextBox>
<asp:Button ID="cmdSearchCity" runat="server" Text="Search"
style="margin-left:25px" CssClass="btn" OnClick="cmdSearchCity_Click"/>
<br />
<asp:GridView ID="GridHotels" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" OnSelectedIndexChanged="GridHotels_SelectedIndexChanged"
CssClass="table">
<Columns>
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:Button ID="cmdHSel" runat="server" Text="Select"
CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
So, when we run, we get/see this:
Now, in above I DID use CommmandName = "select" because I wanted the select row to work. (and I beyond hate all those extra templates). So I used this code to highlight the row.
protected void GridHotels_SelectedIndexChanged(object sender, EventArgs e)
{
// user selected this row - highlight it
int RowIX = GridHotels.SelectedIndex;
GridViewRow gRow = (GridViewRow)GridHotels.Rows[RowIX];
if ((ViewState["MySel"] != null) && ((int)ViewState["MySel"] != RowIX))
{
GridViewRow gLast = GridHotels.Rows[(int)ViewState["MySel"]];
gLast.CssClass = "";
}
gRow.CssClass = "alert-info";
ViewState["MySel"] = RowIX;
}
Ok, so far so simple. And the search button in above is this:
protected void cmdSearchCity_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels ", conn))
{
if (txtSearchCity.Text != "")
{
// filter grid by city
cmdSQL.CommandText += " WHERE City = #City";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtSearchCity.Text;
}
conn.Open();
cmdSQL.CommandText += " ORDER BY HotelName";
GridHotels.DataSource = cmdSQL.ExecuteReader();
GridHotels.DataBind();
}
}
}
Again, really simple.
Ok, now the money shot. Now the Rosetta stone. Now the beef, now the magic, now the amazing!!!
The above as noted was placed in a "div", and has a update panel.
So, now lets drop in another grid!!!
We going to display some people, and pop the above hotel selector grid!!
So, we now have this:
<asp:GridView ID="GPeople" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="Firstname" HeaderText="Firstname" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Province" HeaderText="Province" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="cmdGetHotel" runat="server" Text="Hotels"
OnClick="cmdGetHotel_Click"
OnClientClick="return mypop(this);"
/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadPeople();
}
void LoadPeople()
{
GPeople.DataSource = MyRst("SELECT * from People Order by FirstName");
GPeople.DataBind();
}
So we now have a grid of people. We now want to on a row click, pop up the hotel list.
So, I suggest jQuery.UI, as is much better (and cleaner then bootstrap dialog).
So we have this row click in above:
<asp:Button ID="cmdGetHotel" runat="server" Text="Hotels"
OnClick="cmdGetHotel_Click"
OnClientClick="return mypop(this);"
/>
So in above, we have both a server side button, and then a client side js function that pops up the dialog (and ONLY returns true if we hit ok.
So, now all we need is the js code to pop up the dialog. That code is this:
<script>
selok = false;
function mypop(btn) {
if (selok)
return true;
var mydiv = $("#hoteldialog1")
mydiv.dialog({
modal: true, appendTo: "form",
title: "Test dialog", closeText: "",
width: "40%",
position: { my: 'left top', at: 'right bottom', of: btn },
buttons: {
Ok: (function () {
selok = true;
btn.click()
}),
Cancel: (function () {
mydiv.dialog("close")
})
}
});
return false;
}
</script>
(set hotel grid display:none - jquery.ui will manage this).
So, now we get this:
So we are free to search, have post-backs, and of course select the row.
If the user hits ok, then the first grid button code runs. I did NOT use the selected index change event for that first grid (I could have), but I used this code:
protected void cmdGetHotel_Click(object sender, EventArgs e)
{
Debug.Print("hotel grid click");
Button btn = (Button)sender;
GridViewRow gRow = (GridViewRow)btn.Parent.Parent;
Debug.Print("Grid row = " + gRow.RowIndex);
Debug.Print("PK = " + GPeople.DataKeys[gRow.RowIndex]["ID"].ToString());
Also note, that while the pop grid is hidden? We can STILL get any data from that row, since the selected index of that grid does persist!!
eg:
GridViewRow gRow = (GridViewRow)GHotels.Rows[GHotels.SelectedIndex];
Debug.Print("Grid row = " + gRow.RowIndex);
Debug.Print("PK = " + GPeople.DataKeys[gRow.RowIndex]["ID"].ToString());
// cells collection, or find control to grab any other value
So, I think you should dump the bootstrap dialog.
Put your 2nd nice grid + searching, post backs - what ever you want into a div with a name, and use jQuery.UI to pop the grid. This will allow searching, post backs and then when the user selects the row and hits ok, then you are now free to close this dialog, and you have "index" of that pop set for you.
I would like to get the values from both the date fields shown in my GridView and input them in the TextBox shown below in the Panel by clicking a button. I can't seem to get the date values by using the rowindex and the corresponding cell.
This is my GridView
<asp:GridView ID="ClientContracts" runat="server" CssClass="table table-hover table-sm" ItemType="ScheduleStarterKit.ViewModels.ContractInfo"
DataKeyNames="ContractId"
AutoGenerateColumns="false"
OnRowCommand="ClientContracts_RowCommand">
<Columns>
<asp:ButtonField CommandName="Select" Text="Edit" ControlStyle-CssClass="btn btn-secondary btn-xs" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:TemplateField HeaderText="From">
<ItemTemplate><%# Item.Duration.From.ToLongDateString() %></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To">
<ItemTemplate><%# Item.Duration.To.ToLongDateString() %></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I want the DateTime from Cells 2 and 3 and input it into the corresponding TextBox below
<asp:Panel ID="AddEditPanel" runat="server" Visible="false">
<hr />
<asp:Label ID="Label1" runat="server" AssociatedControlID="ContractTitle">Contract Title</asp:Label>
<asp:TextBox ID="ContractTitle" runat="server" CssClass="form-control" />
<asp:Label ID="Label2" runat="server" AssociatedControlID="Requirements">Requirements</asp:Label>
<asp:TextBox ID="Requirements" runat="server" CssClass="form-control" TextMode="MultiLine" Rows="3" />
<asp:Label ID="Label3" runat="server" AssociatedControlID="FromDate">Duration</asp:Label>
<div class="form-inline">
<div class="form-group row">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">From</span>
</div>
<asp:TextBox ID="FromDate" runat="server" CssClass="form-control" TextMode="Date" />
<div class="input-group-append">
<div class="input-group-prepend">
<span class="input-group-text">To</span>
</div>
<asp:TextBox ID="ToDate" runat="server" CssClass="form-control" TextMode="Date" />
</div>
</div>
<asp:LinkButton ID="SaveContract" runat="server" CssClass="btn btn-primary" OnClick="SaveContract_Click">Save</asp:LinkButton>
</div>
</div>
</asp:Panel>
This is my code behind
int rowIndex = Convert.ToInt32(e.CommandArgument);
ContractTitle.Text = ClientContracts.Rows[rowIndex].Cells[1].Text;
FromDate.Text = ClientContracts.Rows[rowIndex].Cells[2].Text;
ToDate.Text = ClientContracts.Rows[rowIndex].Cells[3].Text;
Ok, there are quite a few ways to do this.
First up:
The event that triggers (due to the CommandName="Select" - VERY important - row index changed will NOT fire if you don't have this).
So, in event GridView SelectedIndexChanged
You can do this IN EVENT Selected index changed:
GridViewRow gV = ClientContracts.SelectedRow;
FromDate.Text = gV.Cells[2].Text;
ToDate.Text = gV.Cells[3].Text;
however, your date fields are now text, and you might well want to keep then as date value types.
You can also in place of a buttonField, drop in a actual asp button. Say like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select"
CommandName="Select"
MyStartDate = '<%# Items.Duration.From %>'
MyEndDate = '<%# Items.Duration.From %>' />
</ItemTemplate>
</asp:TemplateField>
Note how we simple add some custom tags.
now, in row selected index changed?
we go:
Dim gV As GridViewRow = GridView1.SelectedRow
Dim MyButton As Button = gV.FindControl("btnSelect")
' startdate = MyButton.Attributes("MyStartDate")
I figured it out! Sorry if how I asked my question was hard to understand.
I simply had to change my FromDate.Text and ToDate.Text code behind to this
FromDate.Text = DateTime.Parse((ClientContracts.Rows[rowIndex].Cells[2].Controls[0] as DataBoundLiteralControl).Text).ToString("yyyy-MM-dd");
ToDate.Text = DateTime.Parse((ClientContracts.Rows[rowIndex].Cells[3].Controls[0] as DataBoundLiteralControl).Text).ToString("yyyy-MM-dd");
I need to Edit and Delete Row of GridView using C# ASP.NET.
I tried once and able to fill the data in TextBox after click on Edit Button,But I have also one Image to Edit and what I need is when user will click on Edit Image, The Image will also Display in proper place to Edit.In case of Delete part I have Image in Anchor Tag and I need which event I should pass from GridView and define in code behind page so that I can do the operation.
faq.aspx:
<div class="col-md-6">
<label for="question" accesskey="T"><span class="required">*</span> Question</label>
<asp:TextBox ID="TextBox1" runat="server" size="30" value="" name="question" ></asp:TextBox>
<div id="noty" style="display:none;" runat="server"></div>
<label for="answer" accesskey="A"><span class="required">*</span> Answer</label>
<asp:TextBox ID="TextBox2" runat="server" size="30" value="" name="answer" ></asp:TextBox>
<div id="Div1" style="display:none;" runat="server"></div>
</div>
<div class="col-md-6 bannerimagefile">
<label for="insertimage" accesskey="B"><span class="required">*</span> Insert Image</label>
<asp:FileUpload runat="server" class="filestyle" data-size="lg" name="insertimage" id="FileUpload1" onchange="previewFile()" />
<label for="bannerimage" accesskey="V"><span class="required">*</span> View Image</label>
<div style="padding-bottom:10px;">
<asp:Image ID="Image3" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" />
</div>
<div class="clear"></div>
<asp:Button ID="Button1" runat="server" Text="Submit" class="submit"
onclick="Button1_Click" />
</div>
</div>
</div>
</div>
<!--end_1st_faq_add_div-->
<!--2nd_list_banner_view_div-->
<div class="widget-area">
<h2 class="widget-title"><strong>FAQ List</strong></h2><asp:HiddenField ID="HiddenField1" runat="server" />
<div class="streaming-table margin-top-zero padding-top-zero">
<div class="table-responsive">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Width="100%" CssClass="table table-striped table-bordered margin-top-zero"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:TemplateField HeaderText="Sl No">
<ItemTemplate>
<asp:Label ID="faqid" runat="server" Text='<%#Eval("FAQ_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Question" >
<ItemTemplate>
<asp:Label ID="question" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Answer" >
<ItemTemplate>
<asp:Label ID="answer" runat="server" Text='<%#Eval("Answer") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" border="0" name="bannerimage" style="width:70px; height:70px;" ImageUrl='<%# "/Upload/" + Convert.ToString(Eval("Image")) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" >
<ItemTemplate>
</i>
<a href=" " data-toggle="tooltip" title="" class="btn btn-xs btn-danger" data-original-title="Delete"><i class="fa fa-times"></i>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
faq.aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
int index = Convert.ToInt32(e.NewSelectedIndex);
TextBox1.Text = GridView1.Rows[index].Cells[1].Text;
TextBox2.Text = GridView1.Rows[index].Cells[2].Text;
HiddenField1.Value = GridView1.Rows[index].Cells[0].Text;
Button1.Text = "Update";
}
Please help me to resolve this issue.
I see that you have only item temples in grid view.
Hence I'm going to tell you two ways to do this:
1) Add edit template in grid view and handle the OnRowEditing event of grid view.
2) Add a hyperlink with key of row and link to another page where you can design the editor like you have done in this page by pre-populating the data using the key(primary key)
it is better that you use Modern data control like 'entitydataSource' or 'linqdateSource' or 'sqlDataSource' and bind your gridview by them .
using 'itemtemplate' for all rows is not a good way , instead fill you grid with 'dataSource' and use 'itemTemplate' for delete or Edit Button . send button name As commandName and rowID As commandArgument to gridViewItemCommand event in code behind.
in code behindin in GridviewItemcommand_Event with switch statement loop through itemCommands like this :
int itemID = int.parse(e.commandArgument)
switch(e.commandName)
{
case 'DoEdite' :{//some Code
Viewstate["ID"] = itemID;
break;}
case 'DoDelete' :{//some Code
break;}
}
you have the itemID(e.commandeArgument) and know which button clicked(e.commandName) .so you can do what you want.
In edit Mode when you send data to textBoxes use viewstate or other collection to hold your dataID because of after Edit, for Update edited date
you need it,
I have added a like button on my product listview, and the like button suppose to get the value of the ads title and Adsid and the userid whose clicked on this like btn and then the code should store this add in favorite table as it mention in the code but i have a problem as i am still biggner in c# and i dont know how fix it very well could you please help with that(fix the below code cuz I am getting error message:
"Error 3 The name 'Adstitlinkbtn' does not exist in the current context
Error 2 The name 'Labeladsid' does not exist in the current context"
and aslo i will be thankfull if you add a message to user that in case if he didnt login and he click on the likebtn will recive a message " Please login to add this ads to your favorite list".
you can find this screen record that may can explain what i am meaning
screen record
Many thanks for all of you
protected void likebtn_Click(object sender, ImageClickEventArgs e)
{
SqlConnection likecn = new SqlConnection(cs);
SqlCommand likecmd = new SqlCommand();
string sqlstatment = "INSERT INTO favourite (AdsID, UID, AdsTit) VALUES (#AdsID,#UID,#AdsTit)";
likecmd.Connection = likecn;
likecmd.CommandType = CommandType.Text;
likecmd.CommandText = sqlstatment;
//Insert the parameters first
likecmd.Parameters.AddWithValue("#AdsID", Labeladsid);
likecmd.Parameters.AddWithValue("#UID", Session["UsrNme"]);
likecmd.Parameters.AddWithValue("#AdsTit", Adstitlinkbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(likecmd);
DataSet ds = new DataSet();
ad.SelectCommand = likecmd;
ad.Fill(ds);
Response.Write("This Ads has been added to your Fovarite List");
}
<asp:ListView ID="adsshow" runat="server" DataSourceID="locationdatalistshow"
style="text-align: left" >
<ItemTemplate>
<div class="templist">
<asp:Label ID="Labeladsid" runat="server" Text='<%# Eval("AdsID") %>' style="color: #ffffff"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" Height="88px" Width="91px"
CssClass="imag1" ImageUrl='<%# "/images/AdsImgs/" + Eval("Img1") %>'
PostBackUrl='<%# "AdsDetails.aspx?Img1=" + Eval("AdsID") %>' />
<asp:LinkButton ID="Adstitlinkbtn" runat="server"
style="font-weight: 700; color: #0066FF" Text='<%# Eval("AdsTit") %>'
CssClass="adstit" onclick="Adstitlinkbtn_Click"
PostBackUrl='<%# "AdsDetails.aspx?AdsTit=" + Eval("AdsID") %>' ></asp:LinkButton>
<br />
<asp:Label ID="AdsDescLabel" runat="server" Text='<%# Eval("AdsDesc") %>'
CssClass="adsdisc" />
<br /><br />
<br /><br />
<asp:Label ID="CountryLabel" runat="server" Text='<%# Eval("Country") %>'
style="font-family: Arial, Helvetica, sans-serif; font-size: small" />
-
<asp:Label ID="StateLabel" runat="server" Text='<%# Eval("State") %>'
style="font-family: Arial, Helvetica, sans-serif; font-size: small" />
-
<asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>'
style="font-size: small; font-family: Arial, Helvetica, sans-serif" />
<div class="adsprice">Price:
<asp:Label ID="AdsPriceLabel" runat="server" style="color: #FF0000"
Text='<%# Eval("AdsPrice") %>' /></div>
<br />
<div class="iconadsbox">
<asp:ImageButton ID="likebtn" runat="server"
ImageUrl="~/iconsimg/favoritestar2.png" OnClick="likebtn_Click" CommandName="like" />
<asp:ImageButton ID="Sndmailtoadder" runat="server"
ImageUrl="~/iconsimg/mailposter.png" OnClick="Sndmailtoadder_Click" />
</div>
<asp:Image ID="Image1" runat="server" CssClass="divideline"/>
</div>
</ItemTemplate>
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="adsshow" PageSize="7">
<Fields>
<asp:NumericPagerField />
<asp:NextPreviousPagerField />
</Fields>
</asp:DataPager>
<br />
</div>
</LayoutTemplate>
</asp:ListView>
Create a bool value to represent whether user has logged in or not (call it bool loggedIn). Wherever your code is to login (you did not post this code), set that bool to be true. Then when the user clicks the 'like' button, in your 'likebtn_Click' method, check the bool:
if(!loggedIn)
{
MessageBox.Show("Please login to add this ads to your favorite list");
return;
}
I believe you have not shown us all your markup. It appears you are inside a grid view or some other collection control. In those controls, the template layout is dynamically generated for each item. So your label and link button controls don't really exist. What you have to do is create a GridView_Command event and in that code you will have access to the controls in that item.
So basically you created a template item and those controls are generated dynamically at runtime, which is why they are not available to you at design time. If you post the rest of your mark up me or anyone else who wants can give you more specific help.
protected void adsshow_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "like")
{
var lblAds = e.Item.FindControl("Labeladsid") as Label;
var lbtn = e.Item.FindControl("Adstitlinkbtn") as LinkButton;
var id = lblAds.Text;
var title = lbtn.Text;
}
}
<asp:ListView ID="adsshow" runat="server" DataSourceID="locationdatalistshow"
style="text-align: left" onitemcommand="adsshow_ItemCommand" >
<ItemTemplate>
...
<asp:ImageButton ID="likebtn" runat="server"
ImageUrl="~/iconsimg/favoritestar2.png" CommandName="like" />
...
Noticed I added a onCommand event to the ListView, and I removed your OnClick event from the imagebutton. I'm not 100% sure about the removing the OnClick event, so if you can please confirm for me that the OnCommand event fires correctly with the OnClick removed from the ImageButton.
So I have this problem with one of my pages, which basically lists out a bunch of comments for a specified student. The comments are supposed to be editable, but I'm having a problem with getting the contents of a row (so I can display the comment content in a TextBox and allow for edits).
The issue is that whenever I access the GridViewRow from the GridView like such:
this.CommentList.Rows[e.NewEditIndex]
It is returning a collection of cells, but whenever I try access the a cell like so: row.Cells[0].Text (where row is the selected GridViewRow object) it doesn't return any values.
Here is my .aspx code:
<asp:GridView ID="CommentList" runat="server" AutoGenerateColumns="False" CellPadding="5"
ShowHeader="false" Width="100%" DataKeyNames="CommentId" OnRowDeleting="CommentList_RowDeleting"
OnRowCancelingEdit="CommentList_RowCancelingEdit" OnRowEditing="CommentList_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Student ID">
<ItemTemplate>
<b>Author:</b>
<%# ((Comment)Container.DataItem).Author.Name %>
<br />
<b>Date:</b>
<%# ((Comment)Container.DataItem).Created %>
<hr style="border-top: solid 1px black" />
<div style="text-align: center;">
<asp:Panel ID="OptionsPanel" runat="server">
<asp:LinkButton ID="DeleteLinkButton" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this comment?');">Delete</asp:LinkButton>
|
<asp:LinkButton ID="EditLinkButton" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</asp:Panel>
<asp:Panel ID="EditOptionsPanel" runat="server" Visible="false">
<asp:LinkButton ID="CancelEditLinkButton" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</asp:Panel>
</div>
</ItemTemplate>
<ItemStyle CssClass="topLeftJustify" Width="200px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Panel ID="ViewCommentPanel" runat="server">
<%# ((Comment)Container.DataItem).Content%>
</asp:Panel>
<asp:Panel ID="EditCommentPanel" runat="server" Visible="false">
<asp:TextBox ID="Comment" runat="server" CssClass="textEntry" TextMode="MultiLine"
Width="100%" Height="100px"></asp:TextBox>
</asp:Panel>
</ItemTemplate>
<ItemStyle CssClass="topLeftJustify" />
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my .aspx.cs code (that relates to the code above):
protected void CommentList_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
GridViewRow row = this.CommentList.Rows[e.NewEditIndex];
((Panel)row.FindControl("OptionsPanel")).Visible = false;
((Panel)row.FindControl("EditOptionsPanel")).Visible = true;
((Panel)row.FindControl("ViewCommentPanel")).Visible = false;
((Panel)row.FindControl("EditCommentPanel")).Visible = true;
// problem is with this line. it doesn't show the contents of the "comment"
((TextBox)row.FindControl("Comment")).Text = row.Cells[0].Text;
}
catch (Exception ex)
{
this.Messages.ChangeMessage(ex.Message, MessageType.Error);
}
}
When you use a TemplateField you cannot use e.Row.Cells[index].Text to access a control text of the cell. I would simply add a Label to the panel.
But you can also try it this way:
Panel ViewCommentPanel = (Panel) e.Row.FindControl("ViewCommentPanel");
LiteralControl objPanelText = ViewCommentPanel.Controls[0] as LiteralControl;
TextBox Comment = (TextBox) row.FindControl("Comment");
Comment.Text = objPanelText.Text;