DropDownList inside GridView inside Repeater Control not working properly - c#

I'm using Repeater control to generate tables on my dashboard. In the repeater, is a gridview to display item details. In the first column og the gridview is a dropdownlist to select an item and on selected index of that item, I'm fetching item details and the billing process continues for each table. Now the problem is that I'm only able to get the item details in the first repeater. Nothing happens when I select an item in another table or repeater. kindly help me with this issue.
Here is my ASPX markup:
<div class="row">
<asp:Repeater ID="rptrTables" runat="server" OnItemDataBound="rptrTables_ItemDataBound">
<ItemTemplate>
<div class="col-md-6">
<div class="card card-info">
<div class="card-header with-border">
<h3 class="card-title"><asp:Label ID="lblTableNumber" runat="server" Text='<%# Eval("TableName") %>'></asp:Label></h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<asp:GridView ID="grdOrder" runat="server" AutoGenerateColumns="false" AllowPaging="true" CssClass="table table-bordered table-hover table-responsive" GridLines="None" PageSize="10" OnRowDataBound="gvRowDataBound">
<Columns>
<asp:CommandField ShowDeleteButton="true" ControlStyle-CssClass="btn btn-danger fa fa-trash" DeleteText="" HeaderText="Remove" />
<asp:BoundField DataField="RowNumber" HeaderText="Sl. No." />
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="drpItemname" runat="server" CssClass="form-control select2" OnSelectedIndexChanged="GetItemDetails" AutoPostBack="true"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblUnitPrice" runat="server" Text='<%# Eval("UnitPrice")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Line Total">
<ItemTemplate>
<asp:Label ID="lblLineTotal" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Add Item" ConvertEmptyStringToNull="False">
<ItemTemplate>
<asp:Button ID="ButtonAdd" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="AddItem" CausesValidation="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</div>
</div>
<div class="card-footer">
<div class="pull-right">
<asp:Button ID="btnSubmit" runat="server" CausesValidation="false" TabIndex="2" CssClass="btn btn-primary" Text="Print KOT" />
<asp:Button ID="Button1" runat="server" CausesValidation="false" TabIndex="2" CssClass="btn btn-primary" Text="Print Final Bill" />
<asp:Button ID="Button2" runat="server" CausesValidation="false" TabIndex="2" CssClass="btn btn-primary" Text="Complete Order" />
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
And my c# code to fetch item details:
protected void GetItemDetails(object sender, EventArgs e)
{
foreach(RepeaterItem rptrItems in rptrTables.Items)
{
GridView gvItems = (GridView)rptrTables.Items[0].FindControl("grdOrder");
foreach (GridViewRow row in gvItems.Rows)
{
DropDownList ddl = sender as DropDownList;
Control ctrl = row.FindControl("drpItemName") as DropDownList;
if (ctrl != null)
{
DropDownList ddl1 = (DropDownList)ctrl;
if (ddl.ClientID == ddl1.ClientID)
{
Label UnitPrice = row.FindControl("lblUnitPrice") as Label;
Label QTTY = row.FindControl("lblQuantity") as Label;
Label UPrice = row.FindControl("lblUnitPrice") as Label;
Label LINETOTAL = row.FindControl("lblLineTotal") as Label;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
if (ctrl != null)
{
if ((ddl1.ID == ddl.ID) && (ddl1.SelectedIndex == ddl.SelectedIndex))
{
string str = "select * from ItemMaster where ItemName='" + ddl1.SelectedItem.ToString() + "'";
SqlCommand com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
UnitPrice.Text = reader["UnitPrice"].ToString();
QTTY.Text = reader["Quantity"].ToString(); ;
decimal totamt = Convert.ToDecimal(QTTY.Text) * Convert.ToDecimal(UnitPrice.Text);
}
reader.Close();
conn.Close();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "swal", "swal('Item already selected, you can increase the quantity instead!', 'warning');", true);
}
}
}
}
}
}
}

There is a problem in your code. you are always selecting the first item from the repeater control,
GridView gvItems = (GridView)rptrTables.Items[0].FindControl("grdOrder");
Change your code to get the item from foreach loop, so your code will be
GridView gvItems = (GridView)rptrItems.FindControl("grdOrder");
try to use rptrItems instead of the first item of the repeater control each time.
Hope this will help.

Related

How do I obtain the DateTime from a GridView and add it into a TextBox when I click a button

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");

my textbox wont get populated on method/button click?

I have a method which executes on button click event where the textbox is set values from database. but the click event does not show the values on screen, it populates the textboxes, I am getting the values in debugger for text box,the click event is somehow clearing the texctboxes after the method is called, how do I rectify this
This is the method
public void DisplayLead(int EID)
{
DS = new DataSet();
DS = DBM.GetLeadByEnquiryID(EID);
Label2.Text = DBM.Message;
Label1.Text = EID.ToString();
if (DS.Tables[0].Rows.Count > 0)
{
hfCustomerId.Value = DS.Tables[0].Rows[0]["ClientID"].ToString();
txtCName.Text = DS.Tables[0].Rows[0]["ClientName"].ToString();
txtEnq.Text = DS.Tables[0].Rows[0]["Enquiry"].ToString();
txtEnqType.Text = DS.Tables[0].Rows[0]["EnqType"].ToString();
EnqDateTextBox.Text = DS.Tables[0].Rows[0]["Date"].ToString();
if (!DBNull.Value.Equals(DS.Tables[0].Rows[0]["Status"].ToString()))
{
DDLStatus.Items.FindByValue(DS.Tables[0].Rows[0]["Status"].ToString()).Selected = true;
}
txtCP.Text = DS.Tables[0].Rows[0]["Contact"].ToString();
txtEmail.Text = DS.Tables[0].Rows[0]["Email"].ToString();
txtPhone.Text = DS.Tables[0].Rows[0]["Phone"].ToString();
txtComment.Text = DS.Tables[0].Rows[0]["Comment"].ToString();
}
Label2.Text = "test value";
DS = null;
}
This is the button Click event
protected void btnSelect_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int EID = Convert.ToInt32(row.Cells[0].Text);
DisplayLead(EID);
}
here is the html part
<div class="col-md-6">
<div class="panel panel-body">
<fieldset>
<!-- Enquiry -->
<div class="form-group">
<label class="control-label" for="enq">Enquiry</label>
<div class="">
<asp:TextBox ID="txtEnq" runat="server" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" CssClass="errmsg" ControlToValidate="txtEnq" Display="Dynamic" ErrorMessage="Enquiry is required" validationgroup="LeadsForm"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<label class="control-label" for="type">Enquiry Type</label>
<div class="">
<asp:TextBox ID="txtEnqType" runat="server" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" CssClass="errmsg" ControlToValidate="txtEnqType" Display="Dynamic" ErrorMessage="Type of Enquiry required" validationgroup="LeadsForm" ></asp:RequiredFieldValidator>
</div>
</div>
</fieldSet>
</div>
</div>
</div>
On Page Load
protected void Page_Load(object sender, EventArgs e)
{
Label mpLabel = (Label)Page.Master.FindControl("lblWelcome");
Literal TTLabel = (Literal)Page.Master.FindControl("pagetitle");
if ((mpLabel != null) && (TTLabel != null))
{
mpLabel.Text = "Leads";
TTLabel.Text = "Leads";
}
if (Request.QueryString["Lead"] != null)
{
EID = Convert.ToInt32(Request.QueryString["Lead"].ToString());
if (!IsPostBack)
{
DisplayLead(EID);
}
}
if (!IsPostBack)
{
LoadGrid();
}
//if(!EID.Equals(null) )
// {
// DisplayLead(EID);
// }
}
<div class="panel panel-success">
<div class="panel-heading">Current Leads</div>
<div class="panel-body" style="overflow-x:auto">
<asp:GridView ID="GridView1" CssClass="table table-bordered table-striped table-responsive example2" EnableViewState="true" AutoGenerateSelectButton="false" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" runat="server">
<Columns>
<asp:BoundField DataField="SNo" HeaderText="S.No" />
<asp:BoundField DataField="ClientName" HeaderText="Client" />
<asp:BoundField DataField="Enquiry" HeaderText="Enquiry" />
<asp:BoundField DataField="EnquiryType" HeaderText="EnquiryType" />
<asp:BoundField DataField="DateofEnq" HeaderText="Date" DataFormatString = "{0:dd-MMM-yyyy}" />
<asp:BoundField DataField="StatusOfEnq" HeaderText="Status" />
<asp:BoundField DataField="ContactPerson" HeaderText="Contact Person" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="ContactPhone" HeaderText="Phone" />
</Columns>
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%#Eval("SNo")%>' OnClick="btnSelect_Click" CssClass="btn btn-danger btn-xs margin-bottom" CausesValidation="false" />
<asp:Button type="button" runat="server" Text="Status" ID="btnStatus" CommandName="status" CommandArgument='<%#Eval("SNo")%>' OnCommand="btnStatus_Command" CssClass="btn btn-info btn-xs" CausesValidation="false" data-toggle="modal" data-target="#myModal" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>

Why Rowcommand event of a gridview is not getting fired ?

I am facing a kind of weird problem.
Problem:
When I click a link button inside a grid view then RowCommand event of a grid view is getting fired when deployed on a localhost but not when deployed on the IIS i.e. client system. I have also tried a link button inside grid view but that's also not getting fired.
Solution: (Temporary)
When I disabled ValidateRequest on the top of the .aspx page. It worked.
What should I do?
So what can be the possible solution for it? I have googled but nothing good came up.
Code:
<asp:GridView ID="gvAppliedWorks" runat="server" OnRowCommand="gvAppliedWorks_RowCommand" AutoGenerateColumns="false" DataKeyNames="AppliedWorkID, ContractorID" EmptyDataText="No Data Found"
CssClass="table table-responsive table-bordered table-striped" OnRowDataBound="gvAppliedWorks_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Form No">
<ItemTemplate>
<asp:Literal ID="liFormNo" runat="server" Text='<% #Eval("FormNo")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company Name">
<ItemTemplate>
<asp:Literal ID="liCompanyName" runat="server" Text='<% #Eval("Name")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Financial Bid">
<ItemTemplate>
<asp:Label ID="txtBidAmount" runat="server" CssClass="control-label" Text='<% # string.Format("{0:n2}", Eval("FinancialMoney").ToString())%>' />
%
<asp:Label ID="ddlBidPer" runat="server" CssClass="control-label" Text='<%# Eval("AboveBelow").ToString() %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Awarded Percentage">
<ItemTemplate>
<div class="pull-left">
<asp:HiddenField ID="hdnIsAwarded" Value='<%# Eval("IsAwarded") %>' runat="server" />
<asp:TextBox ID="txtAwardedBid" Text='<%#Eval("AwardedBid")%>' Style="width: 70px !important;" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="pull-left" style="margin-top: 7px">
% <%# Eval("AboveBelow").ToString() %>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:TextBox ID="txtRemarks" Text='<%#Eval("Remarks")%>' runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Award Tender">
<ItemTemplate>
<asp:LinkButton ID="lnkAward" runat="server"
CommandArgument='<%# Eval("AppliedWorkID") %>' CommandName="award"
CssClass="btn btn-sm btn-danger" Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>'
Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' CausesValidation="false" Text="Award"></asp:LinkButton>
<ajax:ConfirmButtonExtender ID="cbe" runat="server" DisplayModalPopupID="mpe" TargetControlID="lnkAward">
</ajax:ConfirmButtonExtender>
<ajax:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkAward" OkControlID="btnYes"
CancelControlID="btnNo" BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
<asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none">
<div class="header">
Confirmation
</div>
<div class="body">
Are you sure to Award this Work?
</div>
<div class="Popupfooter" align="right">
<asp:Button ID="btnYes" CssClass="btn btn-sm btn-danger" runat="server" Text="Yes" />
<asp:Button ID="btnNo" CssClass="btn btn-sm btn-primary" runat="server" Text="No" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText='Action'>
<ItemTemplate>
<asp:LinkButton ID="btnBlackList" runat="server" OnClick="btnBlackList_Click" Visible='<%# Convert.ToBoolean( Eval("IsAwarded"))== false? true:false%>' Enabled='<%# Convert.ToBoolean(Eval("IsBlackList")) == true ? false: true %>' Text='Defective'
CssClass="" ToolTip="Blacklist"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
**.cs**
protected void gvAppliedWorks_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
// GridViewRow gr = ((GridViewRow)((Control)sender).Parent.Parent);
if (e.CommandName == "award")
{
GridViewRow gr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int AppliedWorkID = e.CommandArgument.ToInt32(); //gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
TextBox txtAwardedBid = gr.FindControl("txtAwardedBid") as TextBox;
TextBox txtRemarks = gr.FindControl("txtRemarks") as TextBox;
Label txtBid = gr.FindControl("txtBidAmount") as Label;
Label lblAboveBelow = gr.FindControl("ddlBidPer") as Label;
string AboveBelow = lblAboveBelow.Text;
Decimal BidAmount = txtBid.Text.ToDecimal();
if (String.IsNullOrEmpty(txtRemarks.Text))
{
Utility.Msg_Error(this.Master, "Remarks Required!!!");
return;
}
Decimal AwardedBid = string.IsNullOrEmpty(txtAwardedBid.Text.Trim()) ? 0 : txtAwardedBid.Text.Trim().ToDecimal();
string Remarks = txtRemarks.Text;
if (AwardedBid != BidAmount)
{
Utility.Msg_Error(this.Master, "Financial Bid must be equal to Awarded Percentage");
return;
}
if (ClsTender.IsReceivedSubMainOffice(AppliedWorkID, LoginUserID, AwardedBid, Remarks, BidAmount, AboveBelow))
{
Utility.Msg_Success(this.Master, "Work Awarded Successfully!!!");
fill_gvAppliedWorks(labNitNo.Text.Replace("NIT No :", "").ToInt32(), labWorkNo.Text.Replace("Work No :", "").ToInt32());
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
It sounds like your page is trying to submit what it thinks is potentially dangerous content if setting the ValidateRequest = false solves the issue. Is it possible that one of the controls on your page is sending html or something like that?
If one of your controls needs to send HTML then you can overcome this by adding an attribute to your model.
[AllowHtml]
[Required]
public string article_content { get; set; }
This will allow html to be entered into the control.

Get TextBox Text value in a button

I'm trying to get the value of txt_MRP in the codebehind but it keeps giving me
The name "txt_MRP" doesn't exist in this current context
Why is this reference not available? How can I get it?
(The button that I am pressing is btn_add_to_cart_Click)
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-4">
<asp:DataList ID="DataList3" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
<ul id="etalage">
<li>
<img id="Img1" class="etalage_thumb_image" runat="server" src='<%# Eval("Fotografia1") %>' />
<img id="Img2" class="etalage_source_image" runat="server" src='<%# Eval("Fotografia2") %>' />
</li>
</ul>
<br />
</ItemTemplate>
</asp:DataList>
</div>
<div class="col-lg-6">
<asp:DataList ID="DataList1" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<div id="product_name_width">
<asp:Label ID="Product_nameLabel" runat="server" CssClass="product_name" Text='<%# Eval("Nombre") %>' />
<br />
</div>
<span id="rs">₡</span><asp:Label ID="MRPLabel" CssClass="price" runat="server" Text='<%# Eval("Precio") %>' />
<br />
<br />
<span id="brand_name">Marca</span>
<asp:Label ID="BrandLabel" runat="server" CssClass="brand" Text='<%# Eval("Marca") %>' />
<br />
</div>
<div class="form-group">
<label> Cantidad </label>
<asp:TextBox CssClass="form-control" ID="txt_MRP" runat="server" ></asp:TextBox>
</div>
<div id="buy_now_css" runat="server">
<ul>
<li>
<asp:Button ID="btn_add_to_cart" CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnClick="btn_add_to_cart_Click" />
</li>
<li>
<asp:Button ID="btn_buy_now" CssClass="btn btn-success" runat="server" Text="Comprar" OnClick="btn_buy_now_Click" />
</li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID="DataList2" runat="server" DataKeyField="ID" DataSourceID="SqlDataSource1">
<ItemTemplate>
<h2>Descripcion</h2>
<div id="Description_width">
<asp:Label ID="DetailLabel" CssClass="description" runat="server" Text='<%# Eval("Descripcion") %>' />
</div>
</ItemTemplate>
</asp:DataList>
</div>
</div>
txt_MRP does not exist because it is in a DataList Control. It is only available inside the scope of the Control.
If you want to get the value you have to use another method.
Change the button event from Onclick to OnCommand and add a CommandName and set the ItemIndex as CommandArgument.
<asp:Button ID="btn_add_to_cart" CommandName="addToCart" CommandArgument='<%# Container.ItemIndex %>' CssClass="btn btn-primary" runat="server" Text="Añadir al Carrito" OnCommand="btn_add_to_cart_Command" />
And in code behind
protected void btn_add_to_cart_Command(object sender, CommandEventArgs e)
{
//check the correct commandname
if (e.CommandName == "addToCart")
{
//get the row number from the commandargument
int itemIndex = Convert.ToInt32(e.CommandArgument);
//find the texbox in the correct row with findcontrol
TextBox textBox = DataList1.Items[itemIndex].FindControl("txt_MRP") as TextBox;
//do stuff with the value
Label1.Text = textBox.Text;
}
}
You have to assign the delegate or button. For instance:
var button = new Button();
button.Click += new EventHandler("btnAddToCart");
You also may need a CommandArgument, to be able to send a specific value back. But to actually register the click event would be like the above.

Edit Image and Delete Row from GridView using c# ASP.NET

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,

Categories

Resources