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

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,

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

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.

Access TextBox in DataList by ID from Button-Click handler in codebehind

I have a textbox which is kept inside Datalist. I need to find it via ID, so that i can insert text written to that textbox to the database.Here is my aspx page containing textbox.
<asp:Content ID="Content1" ContentPlaceHolderID="ccont" Runat="Server">
<div id="ccont">
<asp:DataList ID="mydatalist" ItemStyle-CssClass="lft_c_down" runat="server">
<ItemTemplate>
<div id="wholeC">
<div id="ctop">
<div id="lft_l">
<div id="lft_c_top">
<asp:Image runat="server" ImageUrl='<%#DataBinder.Eval(Container.DataItem,"ipath")%>' Height="250px" Width="300px" />
<br/>
</div>
<div id="lft_c_down">
<b>Product Name:</b>
<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"products") %>' runat="server" />
<br/>
<b>brand:</b>
<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"brand") %>' runat="server" />
<br/>
<b>Price:</b>
<asp:Label ID="Label1" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
</div>
</div>
<div id="lft_r">
<b>Details:</b>
<asp:Label ID="Label2" Text='<%#DataBinder.Eval(Container.DataItem,"description") %>' runat="server" />
</div>
</div>
<div id="cmt">
<asp:TextBox ID="tb_cmt" runat="server" Height="35px" Width="620" placeholder="comment.." />
<asp:Button ID="Button1" runat="server" Text="Comment" backcolor="black" BorderStyle="None" Font-Names="Consolas" Font-Overline="False"
ForeColor="White" Height="34px" Width="108px" OnClick="cmt_Click" />
</div>
</div>
</ItemTemplate>
</asp:DataList>
</div>
The Textbox with ID="tb_cmt" is the text box i want to access in my code behind as:
protected void cmt_Click(object sender, EventArgs e)
{
// how to get the TextBox?
sq.connection();
SqlCommand cmd = new SqlCommand("insert into comment(ecomment,sid) values(#myecomment,#mysid)", sq.con);
cmd.Parameters.AddWithValue("#myecomment",tb_cmt.text)//but here tb_cmt is not recognized.
}
You can use the NamingContainer property of the button that was clicked to get the DataListItem. Then you just have to use FindControl to get the reference to your TextBox:
protected void cmt_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
DataListItem item = (DataListItem) btn.NamingContainer;
TextBox txt = (TextBox) item.FindControl("tb_cmt");
//... save
}

Add Repeater items to Listbox

I have a Repeater which contains Eval commands and a Button (Which I can't access) I would like to access this button and when clicked insert one of the Eval commands (Eg. Car Model) into a listbox I have on the same page.
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
<asp:Repeater ID="Repeater2" runat="server" DataSourceID="AccessDataSource1" DataMember="DefaultView" OnItemDataBound="Repeater2_ItemDataBound">
<ItemTemplate>
<div>
<p><img src="carImages/<%#Eval("Artwork")%>" /></div>
<div class="col-xs-4">
<h4><%# Eval("Make")%> (<%# Eval("Year") %>)</h4>
<p><%# Eval("Model")%></p>
<p><%# Eval("Colour")%></p>
<p><%# Eval("Type")%></p>
<div>
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
</div>
</a>
</div>
</ItemTemplate>
Just add your oncommand argument to the repeated button
<asp:Button ID="modelButton" CommandArgument='<%# Eval("Model") %>' OnCommand="CommandBtn_Click" Text='<%# "Add Model to List:" + Eval("Model") %>' runat="server" />
you can grab the eval in the behind code
void CommandBtn_Click(Object sender, CommandEventArgs e){
var command = e.CommandArgument;
// Do whatever with it here
}
That will get the evaluated model

Categories

Resources