ASP.net gridview cant update image - asp.net

So i'm a newbie in asp.net. I have this college project which need to use update function. I made the update function, its work fine for all columns except for picture's column. Its not updating picture database, and show the previous picture in the gridview. The pictures in the folder already updated but the gridview just show the previous picture (not the updated one). I need your help please thank you :)
this is the gridview aspx code, if update button was clicked, it will redirect to another page.
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Images" ItemStyle-Height="50px" ItemStyle-Width="50px" >
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("pic") %>'/>/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="nama" HeaderText="nama" />
<asp:BoundField DataField="harga" HeaderText="harga" />
<asp:BoundField DataField="stok" HeaderText="stok" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" wID='<%# Eval("Id") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
this is the Page_Load function
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}
public void loadData()
{
GridView1.DataSource = repo.getAll();
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) loadData();
}
and redirected to update aspx
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:FileUpload ID="pic" runat="server" />
<br />
<asp:TextBox ID="name" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="price" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="stok" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Button" OnClick="btnUpdate_Click" />
This is the update function of btnUpdate in update aspx
protected void btnUpdate_Click(object sender, EventArgs e)
{
string ext = System.IO.Path.GetExtension(pic.FileName);
string nama = name.Text;
int harga = Int32.Parse(price.Text);
int stock = Int32.Parse(stok.Text);
Table update = (Table)Session["updateWatch"];
string pict = "..\\Pictures\\Watch Pictures\\" + update.Id + ext;
bool updateStatus = repo.update(update.Id, pict, nama, harga, stock);
if (updateStatus == false) Label1.Text = "fail";
else
{
string subPic = update.pic.Substring(3);
string path = Server.MapPath("~") + subPic;
string savepath = Server.MapPath("~/Pictures/Watch Pictures/");
System.IO.File.Delete(path);
pic.SaveAs(savepath + update.Id + ext);
Response.Redirect("WebForm1.aspx");
}
}
this is the update function in repository
public bool update(int id, string pic, string nama, int harga, int stok)
{
Table updateW = (from x in de.Tables where x.Id == id select x).FirstOrDefault();
updateW.pic = pic;
updateW.nama = nama;
updateW.harga = harga;
updateW.stok = stok;
de.SaveChanges();
if (updateW == null) return false;
return true;
}
this is the code for gridview datasource
public List<Table> getAll()
{
List<Table> watches = (from x in de.Tables select x).ToList();
return watches;
}

Related

Hide button in gridview when field is Null

I have a grid view where some of the rows have attached pictures. when I press Button2 I pull information from the sql record, about which folder on the server that has the pictures.
This works already, but I can not get the button to only be visible in the rows that have image folder attached.
I've googled a long time and found different solutions similar to the following, but I can not get it to work.
What am I doing wrong?
<asp:SqlDataSource ID="SqlDSodinRSSfeb" runat="server"
ConnectionString="<%$ ConnectionStrings:herning_brand_dk_dbConnectionString %>"
SelectCommand="SELECT PubDateTime, Melding, Station, PhotoFolder FROM OdinRSS ">
</asp:SqlDataSource>
<asp:GridView ID="GridView14" runat="server" DataSourceID="SqlDSodinRSSfeb"
AutoGenerateColumns="False" Width="500px" OnRowCommand="Button_RowCommand" >
<Columns>
<asp:BoundField DataField="PubDateTime" HeaderText="Tidspunkt" />
<asp:BoundField DataField="Melding" HeaderText="Melding for udkaldet" />
<asp:BoundField DataField="Station" HeaderText="Station" />
<asp:TemplateField HeaderText="Foto" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhotoFolder") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder") != "Null" %>'
CommandName="ButtonClick" CommandArgument='<%# Eval("PhotoFolder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My .cs
protected void Button_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument != null)
{
switch (e.CommandName)
{
case "ButtonClick":
{
int Folder = Convert.ToInt32(e.CommandArgument);
PhotoList(Folder);
}
break;
}
}
}
void PhotoList(int FolderNumber)
{
var imagePaths = Directory.GetFiles(Server.MapPath("PhotoFolder\\" + FolderNumber));
var imageNames = new string[imagePaths.Length];
for (int i = 0; i < imagePaths.Length; i++)
{
imageNames[i] = imagePaths[i].Substring(imagePaths[i].LastIndexOf("\\") + 1);
}
var dt = new DataTable();
dt.Columns.Add("ImageName", typeof(string));
dt.Columns.Add("ImagePath", typeof(string));
foreach (var imgName in imageNames)
{
DataRow dr = dt.NewRow();
dr["ImageName"] = RemoveExtension(imgName);
dr["ImagePath"] = "PhotoFolder/" + FolderNumber + "/" + imgName;
dt.Rows.Add(dr);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
string RemoveExtension(string imgName)
{
return imgName
.Replace(".jpg", "")
.Replace(".png", "");
}
The sql field "PhotoFolder" is a nvarchar(50). If there is photos for the record, the field has a number from 100 and up, that refares to the folder containing photos. If there are no photo for the record, the field contains "Null"
I have also tried:
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder").ToString() != "Null" %>'
But the button is shown in all rows, not just the ones that has a string(number) in "PhotoFolder"
It can be achieved simple in Inline code
<asp:ImageButton ID="ibtnBranchType1" runat="server" ImageUrl='<%# "~/images/" + Eval("branchtype1")+".png" %>' Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>' Height="20px"/>
Here Eval("branchtype1") we are getting value of id from data table like 1, 2, 3 etc. and our image folder consists images like 1.png, 2.png, 3.png etc.,
Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>'
if value doesn't contain any id it will get null. we will compare it with empty string using ternary operator.
Try this.
Markup
Visible='<%# HideEmptyPhotoFolder(Eval("PhotoFolder")) %>'
Code-Behind
protected bool HideEmptyPhotoFolder(object photoFolder)
{
return photoFolder != null && !String.IsNullOrEmpty(photoFolder.ToString());
}
You can simply do that in GridView RowDataBound event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
As per your question you should write the code for checking the rows containing the image,
you can write the code in RowDatabound event,and set visible property of button to false on that row which doesn't contain image.

Get text of TextBox that Outside the UpdatePanel

<asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="700px" placeholder="Enter Title" ></asp:TextBox>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:AjaxFileUpload ID="AjaxUploadImages" runat="server" AllowedFileTypes="jpg,jpeg,png,gif"
onuploadcomplete="AjaxUploadImages_UploadComplete"/>
</ContentTemplate>
</asp:UpdatePanel>
I want to get the text of TextBox1 on the OnUploadComplete event like this-
protected void AjaxUploadImages_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string path = Server.MapPath("~/images/") + e.FileName;
AjaxUploadImages.SaveAs(path);
string content = TextBox1.Text.ToString();
}
protected void AjaxUploadImages_UploadComplete(object sender,AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string path = Server.MapPath("~/images/") + e.FileName;
AjaxUploadImages.SaveAs(path);
string content = TextBox1.Text.ToString();
}

Firing ImageButton server side event but the page is not updating using ASP.NET UpdatePanel

I've feature to implement which is when user in the GridView footer and press on Enter key the row will be inserted. In the GridView I have 2 <asp:ImageButton> one in <EmptyDataTemplate> and the other in <FooterTemplate> I wrote JavaScript to execute the ImageButton Click event when use is in the last field, the ImageButton Server-Side Click event fired but the page is not updated.
Here is JavaScrip function:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
}
}
Here is the ASPX:
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
...
<asp:GridView ID="grvDonationDist" runat="server" AutoGenerateColumns="False" ShowFooter="True"
DataKeyNames="reciept_num,donation_code" meta:resourcekey="grvDonationDistResource1"
ShowHeaderWhenEmpty="True" BorderWidth="1px" BackColor="White" BorderColor="LightSteelBlue"
CellPadding="0" Font-Name="tahoma" Font-Size="10pt" ForeColor="DarkBlue" HeaderStyle-BackColor="#aaaadd"
GridLines="None">
<EmptyDataTemplate>
<asp:Label CssClass="label" ID="lblEmptyDonationDist" runat="server" Text="No Donations"
meta:resourcekey="lblEmptyDonationDistResource1"></asp:Label>
<tr>
<td>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAdd_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</td>
...
<td>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</td>
</tr>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField FooterText="Total" ShowHeader="False">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtnAdd" runat="server" OnClick="lbtnAddFromFooter_Click" meta:resourcekey="AddResource1"
ImageUrl="Content/images/add.png"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
...
<asp:TemplateField HeaderText="Notes" SortExpression="distribution_remrks" meta:resourcekey="TemplateFieldResource3">
<EditItemTemplate>
...
</EditItemTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDonationNotesFooter" CssClass="textbox" runat="server" meta:resourcekey="txtDonationNotesResource1"
onKeyDown="insertByEnterKey('lbtnAdd');"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Here is VB.NET:
Protected Sub lbtnAddFromFooter_Click(sender As Object, e As EventArgs)
'Footer Add
'Add Insert Logic here
Try
Dim donationDist As New DonationDist
Dim txtDonationValueFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationValueFooter")
Dim txtDonationNotesFooter As TextBox = grvDonationDist.FooterRow.FindControl("txtDonationNotesFooter")
Dim ddlCountryFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlCountryFooter")
Dim ddlPurposeFooter As DropDownList = grvDonationDist.FooterRow.FindControl("ddlNewDonationPurposeType")
Dim chkPartial As CheckBox = grvDonationDist.FooterRow.FindControl("chkPartialFooter")
Dim standInstruct As Label = grvDonationDist.FooterRow.FindControl("lblStandInstructFooter")
Dim donationValue As Decimal = Convert.ToDecimal(txtDonationValueFooter.Text)
'Validation: Donation Value must be > 0
If (donationValue <= 0) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("قيمة الترع يجب ان تكون أكبر من الصفر")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("Donation Value must be greater than 0")
End If
Exit Sub
End If
myDonationDistDataTable = Session("myDonationDistDataTable")
'Validation: Only one donation type per Receipt
For Each row As DataRow In myDonationDistDataTable.Rows
If (row.Item("donation_code") = ddlPurposeFooter.SelectedValue) Then
If (CultureInfo.CurrentUICulture.Name.Contains("ar")) Then
ShowAlert("لا يمكن تكرار الغرض في نفس سند القبض")
ElseIf (CultureInfo.CurrentUICulture.Name.Contains("en")) Then
ShowAlert("You cannot add more than on Donation Type per receipt")
End If
Exit Sub
End If
Next
myDonationDistDataRow = myDonationDistDataTable.NewRow()
myDonationDistDataRow("reciept_num") = 0
myDonationDistDataRow("donation_code") = Convert.ToInt16(ddlPurposeFooter.SelectedValue)
myDonationDistDataRow("donation_name") = ddlPurposeFooter.SelectedItem.Text
myDonationDistDataRow("donation_value") = Convert.ToDecimal(txtDonationValueFooter.Text)
myDonationDistDataRow("country_code") = Convert.ToInt16(ddlCountryFooter.SelectedValue)
myDonationDistDataRow("country_name") = ddlCountryFooter.SelectedItem.Text
myDonationDistDataRow("distribution_remrks") = txtDonationNotesFooter.Text
myDonationDistDataRow("partial") = chkPartial.Checked
myDonationDistDataRow("standing_inst_num") = If(String.IsNullOrWhiteSpace(standInstruct.Text), 0, Convert.ToInt32(standInstruct.Text))
'add the new DataRow to DataTable's Row
myDonationDistDataTable.Rows.Add(myDonationDistDataRow)
Session("myDonationDistDataTable") = myDonationDistDataTable
grvDonationDist.DataSource = myDonationDistDataTable
grvDonationDist.DataBind()
Catch ex As Exception
'TODO: Log the exception
End Try
End Sub
What is wrong with this code? Am I missing something?
you can't do it that way, you will need to add the event to the update panel
javascript:
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
__doPostBack('<%= UpdatePanel.UniqueId %>', '');
}
}
aspx:
<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional" onload="UpdatePanel_Load">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
CS:
protected void UpdatePanel_Load(object sender, EventArgs e)
{
//add your code here
}
if you do not get the _doPostBack in your code you can add it like this..
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.GetPostBackEventReference(this, string.Empty);
}
I solve it just by add return false after the insertByEnterKey() function
onKeyDown="insertByEnterKey('lbtnAdd'); return false;"
Even better solution:
Make the JavaScript Function return False when the user press "Enter Key" otherwise return True.
function insertByEnterKey(buttonId) {
var button = document.getElementById(buttonId);
var keyEvent = event.keyCode;
if (keyEvent == 13) {
button.click();
return false;
} else {
return true;
}
}
and use it in the Textbox like this:
<asp:TextBox ID="txtDonationNotesFooter" runat="server" onKeyDown="return insertByEnterKey('lbtnAdd');"></asp:TextBox>

asp.net datalist select all checkboxes per category

I have a page where users can select different documents files in a datalist control. The documents are categorized based on categories using the on pre-render event handler. Documents are selected based on Checkbox controls (not Checkboxlist). So far so good. What I want to happen next is to put a 'Select All' checkbox beside each Category's name which should select only checkboxes under that category. Here is the datalist control:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" OnPreRender="DataList1_PreRender" DataKeyField="docid" EnableViewState="false">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Font-Underline="True"></asp:Label>
<asp:Label runat="server" id="lbl_cb_all" visible="false">Select All <input runat="server" id="cb_selectall" type="checkbox" value='<%# Eval("catid") %>' /> </asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:Label ID="lbl_categoryname" runat="server" Text='<%# Eval("categoryname") %>' Visible="false" /> <!-- Hide this; only used in Code Behind -->
<input runat="server" id="cb_docid" type="checkbox" value='<%# Eval("docid") %>' />
<asp:Hyperlink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>' Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
and here is the OnPreRender code:
protected void DataList1_PreRender(object sender, EventArgs e)
{
string strTempLabelCategory = "";
foreach (DataListItem item in DataList1.Items)
{
Label lbl_categoryname = item.FindControl("lbl_categoryname") as Label;
if (strTempLabelCategory.ToUpper() != lbl_categoryname.Text.ToString().ToUpper())
{
strTempLabelCategory = lbl_categoryname.Text.ToString().ToUpper();
Label lblHeader = item.FindControl("lblHeader") as Label;
lblHeader.Text = strTempLabelCategory.ToUpper();
Label lbltempdiv = item.FindControl("lbl_cb_all") as Label;
lbltempdiv.Visible = true;
}
}
}
I have looked for something which can work within my code but no luck. And I am too invested in this code to now try Checkboxlist control (not sure if that would help anyway).
Any ideas? I thought I could use: http://www.dotnetcurry.com/ShowArticle.aspx?ID=77 code but not sure how I can make that work? If I can somehow make the select all checkbox tie to a tag and then look for all tag then may be the link's code would help.
Thanks!
Use HiddenFields to store CatID and DocID
Use ASP.NET CheckBoxes instead of HTML-Inputs for both
Handle the Check-All Checkbox' CheckedChanged event:
protected void CheckAllChanged(Object sender, EventArgs e)
{
CheckBox checkAll = (CheckBox)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"));
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = checkAll.Checked;
}
}
on aspx:
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("DocID") %>' />
You also need to EnableViewState=true on the DataList to maintain checkbox state and enable checking/unchecking.
Edit:
Because you have problems to get it running, here's a complete working sample page.
Here are the required controls on aspx(note f.e. <tr runat="server" id="tr_category">):
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>' Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select All
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:CheckBox runat="server" id="cb_docid" />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
Ensure that the DataList is databound only if(!IsPostback), otherwise the checkbox selection will not be maintained:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindDataList();
}
I'm using ItemDataBound instead of PreRender which is important for the ViewState to be reloaded correctly. I've also simplified all:
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex-1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
The CheckAllChanged remains unchanged.
This works as expected even if you select a single document-checkbox and select a category-checkbox afterwards which causes a postback.
I think I got this to work with slight modification of Tim's code. A few points: I had to disable ViewState for the datalist because, otherwise, the check-all trigger was not keeping boxes checked. I don't understand why. Also, there is not ispostback check in the page_load event and the datalist binds on every load. I am not that's 'optimal' or not. I have also made two sets of Asp:RadioButtons: CheckAll and CheckNone, instead of checkboxes. Anyway, here is the relevant code:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" DataKeyField="docid"
EnableViewState="false" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>'
Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select: All
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true"
ID="rb_selectall" GroupName="selectallnone" />
| None
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChangedNone" AutoPostBack="true"
ID="rb_selectnone" GroupName="selectallnone" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("docid") %>' />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:CheckBox runat="server" ID="cb_docid" Value='<%# Eval("docid") %>' />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex - 1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
protected void CheckAllChanged(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
// docCheckBox.Checked = checkAll.Checked;
docCheckBox.Checked = true;
}
}
protected void CheckAllChangedNone(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = false;
}
}
//partial code from the Order button follows; note the use of HiddenField
CheckBox cb = li.FindControl("cb_docid") as CheckBox;
if (cb != null)
{
if (cb.Checked)
{
HiddenField docid = li.FindControl("HiddenDocID") as HiddenField;
string dbcmd = #"Insert Into [order_details] (orderid,docid) Values (" + orderid + "," + docid.Value.ToString() + ")";
protected void chkAllN_CheckedChanged(object sender, EventArgs e)
{
lblSelectedRecord.InnerText = "0";
/*this Foreach Loop performing for find gridview*/
foreach (DataListItem dst in dstMulEmpSalInsert.Items)
{
GridView grd = (GridView)dst.FindControl("grdMulEmpSalInsert");
CheckBox chk_All = (CheckBox)grd.HeaderRow.FindControl("chkAllN");
if (chk_All.Checked == true)
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = true;
txt_Salary.ReadOnly = false;
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
else
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = false;
}
}
}
}

GridView Delete Not Re-Binding

I have a GridView with a delete template field:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="gvCurrentDay" CssClass="gridview" OnRowCommand="gvCurrentDay_RowCommand" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="ClientName" HeaderText="Client" />
<asp:BoundField DataField="ProjectTitle" HeaderText="Project" />
<asp:BoundField DataField="TimeToAdd" HeaderText="Time Allocated" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imbDeleteRow" ImageUrl="~/images/icons/DeleteRed.png" CommandArgument='<%# Eval("RecordID") %>' CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
The code runs when the button is pressed and the database entry is removed from the database, but the GridView is not rebinding, here is the code that controls the delete:
protected void gvCurrentDay_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int RecordID = Convert.ToInt32(e.CommandArgument);
tdl objTdl = new tdl();
objTdl.DeleteEntryForDay(RecordID);
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}
}
And here is the first part of the GetItineryForDay procedure:
protected void GetItineryForDay(DateTime SelectedDate)
{
gvCurrentDay.DataSource = null;
gvCurrentDay.DataBind();
tdl objTdl = new tdl();
DataTable dt = objTdl.GetUsersProjectTimeForDay(SelectedDate, Convert.ToInt32(Request.Cookies["staffid"].Value));
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
int TotalTime2 = Convert.ToInt32(row[7]);
string TotalTime = row[7].ToString() + " minutes";
gvCurrentDay.DataSource = dt;
gvCurrentDay.DataBind();
Can you see from the code any reason why the GridView is not updating? The GridView sits in an UpdatePanel.
Instead of using "Delete" as the CommandName, use something else, like "ManualDelete". "Delete" is usually trapped by RowDeleting and RowDeleted events.
Alternatively, and since "the database entry is removed from the database", you could put your rebind code in the RowDeleted event.
protected void gvCurrentDay_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}

Resources