Trying to Add Insert Row to Footer in GridView ASP.net - c#

I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>

I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.

A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Image upload not working Always get the FALSE value

UI
Image upload part is not working, I want to upload image path in Database but not working, and not bind correctly can't save it, can you please help me, Table to displayed upload image value is always FALSE
ASPX
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="image" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
CODE
#region Detail Save1
private DataTable CreateDetailSave()
{
DataTable dtDetailSave1 = new DataTable();
DataColumn dc1;
dc1 = new DataColumn("intArticleDetailId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intSectionId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intCompoundId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("decSectionWeight");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intMessageId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("strImage");
dtDetailSave1.Columns.Add(dc1);
foreach (GridViewRow row in gvArticle.Rows)
{
DataRow dr = dtDetailSave1.NewRow();
Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
Label lblSectionId = (Label)row.FindControl("lblSectionId");
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");
FileUpload fileupload = (FileUpload)row.FindControl("fileupload");
dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);
dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
dr["intCompoundId"] = ddlCompound.SelectedValue;
dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
dr["intMessageId"] = intMessage.SelectedValue;
dr["strImage"] = fileupload.HasFile;
dtDetailSave1.Rows.Add(dr);
}
return dtDetailSave1;
}
#endregion
#region pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClearControls();
FillArticleDetails();
EnableControls(false);
Session["SearchPopup"] = false;
}
else
{
if (Session["SearchPopup"] != null)
{
SearchPopup = (bool)(Session["SearchPopup"]);
if (SearchPopup != false)
{
MyMPE.Show();
}
else
{
MyMPE.Hide();
}
}
vAdSearchParaList = new List<SearchParametors>();
}
}
#endregion
#region Create Article table
private void createArticleDataTable()
{
if (dt.Columns.Count == 0)
{
dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
dt.Columns.Add(new DataColumn("fileupload", typeof(string)));
}
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
#endregion
#region Compound Grid - Add empty row
private void ArticleGridAddEmptyRow(int newId)
{
DataRow newDr = null;
newDr = dt.NewRow();
newDr["intArticleDetailId"] = 1;
newDr["intSectionId"] = 1;
newDr["strSectionName"] = "";
newDr["intCompoundId"] = "";
newDr["decSectionWeight"] = "";
newDr["intMessageId"] = "";
newDr["strImage"] = "";
dt.Rows.Add(newDr);
if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
{
dtArticleDetails = dt;
}
else
{
dtArticleDetails.Merge(dt);
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
}
#endregion
protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvArticle.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
if (fu != null && fu.HasFile)
{
fu.SaveAs(Server.MapPath("~/Uploaded Images" + fu.FileName));
}
}
full aspx
<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>
<asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvArticle"/>
</Triggers>
</asp:UpdatePanel>
</div>
</div>
gvArticle_rowdatabound
protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
{
}
DataTable CompoundCode = clsArticle.CompoundDataForGrid("");
DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
if (ddlCompoundId != null)
{
ddlCompoundId.DataTextField = "Compound Code";
ddlCompoundId.DataValueField = "Compound Id";
ddlCompoundId.DataSource = CompoundCode;
ddlCompoundId.DataBind();
string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
ddlCompoundId.Items.FindByValue(country).Selected = true;
}
DataTable MsgCode = clsArticle.MessageDataForGrid("");
DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
if (ddlMessage != null)
{
ddlMessage.DataTextField = "Message Name";
ddlMessage.DataValueField = "Message Id";
ddlMessage.DataSource = MsgCode;
ddlMessage.DataBind();
ddlMessage.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
ddlMessage.Items.FindByValue(country).Selected = true;
}
//}
}
}
Your code has lots of issues.
First of all FileUpload control doesn't have AutoPostBack property as well as CommandArgument property so you need a button in each row.
.aspx fragment
<asp:TemplateField HeaderText="upload">
<ItemTemplate>
<asp:FileUpload ID="fileupload" AutoPostBack="true" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="upload">
<ItemTemplate>
<asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" CommandArgument='<%#Eval("PK_FIELD") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
.aspx.cs fragment
protected void btnUpdate_Click(object sender, EventArgs e)
{
FileUpload fu =
((GridViewRow)((WebControl)sender).NamingContainer)
.FindControl("fileupload") as FileUpload;
bool ok = false;
if (fu != null && fu.HasFile)
{
try
{
//possible issue here.
//process NEED PERMISSION to write to this folder
//also some checks with fu.PostedFile are recommended
fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
ok = true;
}
catch (Exception ex)
{
ok = false;
}
}
if (ok)
{
//update DB table and GridViewRow image field.
}
}
I hope this explanation is useful and acceptable.
Update based on your gridview
<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" CssClass="table
table-bordered table-condensed table-hover" AutoGenerateColumns="False"
runat="server" AllowPaging="True" PageSize="15"
OnRowDataBound="gvArticle_RowDataBound"
DataKeyNames="PK_field" **important**
>
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2"
Text='<%# Eval("intArticleDetailId") %>' **Bind is nonsense for label**
runat="server"></asp:Label> **ClientIDMode="Static" remove everiwhere**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>** no edit mode remove**
<asp:Label ID="lblItemTypeEdit" Width="50"
Text='<%# Bind("strCompoundName") %>' ** see above**
ClientIDMode="Static"
AutoPostBack="true"
runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200"
CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' ClientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Images"> <ItemTemplate>
**work with upload. remove wrong attributes**
**AutoPostBack="True"CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static" **
<asp:FileUpload runat="server" ID="uploadFImage" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
** place update button outside to update all columns **
<asp:Button ID="btnUpdate" Text="upload" OnClick="btnUpdate_Click" runat="server" />
//.aspx.cs
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gvArticle.rows)
{
FileUpload fu =
row.FindControl("fileupload") as FileUpload;
bool ok = false;
if (fu != null && fu.HasFile)
{
try
{
//possible issue here.
//process NEED PERMISSION to write to this folder
//also some checks with fu.PostedFile are recommended
fu.SaveAs(Server.MapPath("~/images/" + fu.FileName));
ok = true;
}
catch (Exception ex)
{
ok = false;
}
}
if (ok)
{
//update DB table and GridViewRow image field.
}
}
}
You try to save it with different path than the one you read: Server.MapPath("~/Uploaded Images" + fu.FileName) != <asp:Image ImageUrl="~/Uploaded Images/Default.png" Notice missing / in the save path. Try this code:
protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvArticle.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
if (fu != null && fu.HasFile)
{
fu.SaveAs(Server.MapPath("~/Uploaded Images/" + fu.FileName));
}
}
When a file is selected using FileUpload Control ,then on postback, PostedFile property gets initialized with HttpPostedFile object for the file. Since http request cannot maintain state, so it looses it's state.
FileUpload control will not work with asynchronous postback.So a postback is needed to get the file. One way is to set the triggers for your Upload button
TO PERSIST THE VALUE OF FILEUPLOAD CONTROL, you can store the fileupload object altogether in session and after postback retrieve the values you require from session.
EDIT : Try with the following example.
You are using RowUpdating so my suggestion is use EditItemTemplate along with ItemTemplate so Add this
<EditItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</EditItemTemplate>
along with this:-
<ItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ItemTemplate>
So your TemplateField Image will look like this
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</EditItemTemplate>
</asp:TemplateField>
And for file upload as Lesmian said use this:-
protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvArticle.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("strImage") as FileUpload;
if (fu != null && fu.HasFile)
{
fu.SaveAs(Server.MapPath("~/Uploaded Images/" + fu.FileName));
}
}
Hope this will help you.
In aspx page use updatepanel control to hold the ID's that are generated.
refere the following code.
< asp:TemplateField HeaderText="">
< ItemTemplate>
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="fileUploadPanel">
<ContentTemplate>
<asp:FileUpload runat="server" AutoPostBack="True" ID="fileupload" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="fileupload" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
<ItemTemplate>
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="ImageUploadPanel">
<ContentTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="image" Width="40" Height="40"/>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="image" />
</Triggers>
</asp:UpdatePanel>
</ItemTemplate>
< /asp:TemplateField>
Hope this helps..
The given code has some serious mistakes and also it is not complete. It is really hard to reproduce at my end. Anyhow there are some thing that can be done to solve the problem:
Remove unnecessary code like labels having contain AutopostBack="true".
ClientIdMode="static" in Gridview will produce invalid HTML and may be the cause of your problem, because it will produce HTML elements that have same id values and that will create invalid HTML page. There are various lines of code containing this attribute. Simply remove these.
Third is your aspx code line <asp:PostBackTrigger ControlID="gvArticle"/>. It should point to a button control that causes the postback after you have selected the image. I think, Here save button Id should be used.
Do the changes in your code and still it is not solved, you need to provide full page code for more diagnosis.
Enjoy!
You'll pretty much always get a boolean value (false) since you set the strImage value as such.
dr["strImage"] = fileupload.HasFile;
Check your code under the foreach.
Also, under the gvArticle_RowUpdating() event, you find for the fileupload control where with the value strImage instead of using your defined id fileupload.
protected void gvArticle_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gvArticle.Rows[e.RowIndex];
FileUpload fu = row.Cells[0].FindControl("fileupload") as FileUpload;
if (fu != null && fu.HasFile)
{
fu.SaveAs(Server.MapPath("~/Uploaded Images" + fu.FileName));
}
}
As #Ruban.J said "FileUpload control will not work with asynchronous postback"
means it always have some problem with UpdatePanel, Whenever a Postback occure fileupload lose it states [Its files],
He also said
TO PERSIST THE VALUE OF FILEUPLOAD CONTROL, you can store the fileupload object altogether in session and after postback retrieve the values you require from session.
so breaking all process into small steps
Step 1: You have to save all the fileupload object into session whenever postback occure, for this i think this should be work on pageLoad Event.
if (!IsPostBack)
{
//Bind your gridview 1st time
}
else
{
Dictionary<int, HttpPostedFile> postedFiles = new Dictionary<int, HttpPostedFile>();
foreach (GridViewRow row in gvArticle.Rows)
{
int id = Convert.ToInt16("YourUniqueRowId"); // whaterver your unique id is there
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
// find your fileupload controll for that row
FileUpload fileupload = (FileUpload)row.FindControl("fileupload");
if (fileupload.HasFile)
{
postedFiles.Add(id, fileupload.PostedFile);
}
}
Session["files"] = postedFiles;
}
Also check whether you are getting file info here, by looking into each HttpPostedFile.
Step 2: whenever you need files just get it from session:
if (Session["files"] != null)
{
Dictionary<int, HttpPostedFile> postedFiles = (Dictionary<int, HttpPostedFile>) Session["files"];
}
You can match Key value for deciding which file is for which row and save it to database.
I think in your CreateDetailSave method inside foreach loop you are saving your filename as fileupload.Hasfile which will always return true or false. That's why it is always returning false:
foreach (GridViewRow row in gvArticle.Rows)
{
dr["strImage"] = fileupload.filename; //before it was fileupload.Hasfile
}
Try to change ClientIDMode = Inherit in your FileUpload control and check it is work.

Remove Hyperlink of specif cell in gridview

I've created a gridview, which all values (footer included) are hyperlinks, to export a detail in Excel.
All is working fine, except, when the value is 0, I don't want to permit the hyperlink, so it doesn't create a empty excel.
<asp:GridView ID="dtlist" runat="server" CellPadding="0" CssClass="table tabela caixa " CellSpacing="0" OnRowDataBound="dtlist_RowDataBound" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="true" >
<Columns >
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="LabelT" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:HyperLink runat="server" ID="lnkA" NavigateUrl='<%# String.Format("/Export?name={0}, Eval("name")) %>' Text='<%# Eval("value","{0:#####,##0.00 €}") %>' />
<asp:Label runat="server" ID="lblA" Text='<%# Eval("value","{0:#####,##0.00 €}") %>' Visible="false" />
</ItemTemplate>
<ItemStyle CssClass="alinha-direita" />
<FooterTemplate>
<asp:HyperLink runat="server" ID="lnkTA" />
</FooterTemplate>
<FooterStyle CssClass="alinha-direita" />
<HeaderStyle CssClass="alinha-meio" />
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the RowDataBound:
protected void dtlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Total = 0;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hA = (HyperLink)e.Row.FindControl("lnkA");
Label lA = (Label)e.Row.FindControl("lblA");
if (hA.Text.ToDecimal() == 0)
{
hA.Visible = false;
lA.Visible = true;
}
Total += ((DataRowView)e.Row.DataItem).Row["Ano0"].ToDecimal();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
HyperLink tA = (HyperLink)e.Row.FindControl("lnkTA");
tA.NavigateUrl = String.Format("/ExportStock?name={0}","ZZZZ");
tA.Text = Total0.StringEuro();
}
}
I've tried to ask on the e.Row.RowType == DataControlRowType.DataRow, if the value of the Hyperlink is 0, but if one value on the column is 0 it disables all hyperlinks on that column.
How can I remove only for the 0 cell?
Thanks.
CODE UPDATED

Bind Dropdown list in Gridview footer which is in Tab Control

I am using ASP.NET and Entity Framework and Tab control of AJAX
I have a dropdown list control in gridview which is in TAB control Am not able to bind dropdown list control.
Tab Control --> Gridview --> Dropdown list
My ASP.NET Code is
<ajax:TabContainer ID="TabContainer2" runat="server" CssClass="fancy fancy-green">
<ajax:TabPanel ID="TabPanel1" runat="server">
<HeaderTemplate>
College Toppers
</HeaderTemplate>
<ContentTemplate>
<asp:Panel ID="Panel1" runat="server">
<div>
<asp:GridView ID="GridView1" DataKeyNames="TL_ID" runat="server"
AutoGenerateColumns="False" CssClass="Gridview" ShowFooter="True" OnRowDataBound="GRVToppers_RowDataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="~/Admin/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" /><asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Admin/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Admin/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Admin/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" /><asp:ImageButton ID="imgbtnDelete" CommandName="Delete" runat="server" ImageUrl="~/Admin/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Topper List No">
<EditItemTemplate>
<asp:Label ID="lblEditTpid" runat="server" Text='<%#Eval("TL_ID") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblShowTpid" runat="server" Text='<%#Eval("TL_ID") %>' />
</ItemTemplate>
<ControlStyle Width="10px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Department Name">
<EditItemTemplate>
<asp:DropDownList ID="ddlEditDeptname" runat="server" Width="90" DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="true"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddladdnewDeptname" runat="server" Width="90" DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="True"></asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblShowDeptname" runat="server" Text='<%#Eval("DEPT_NAME") %>' Width="90" />
</ItemTemplate>
<ControlStyle Width="30px" />
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#61A6F8" Font-Bold="True" ForeColor="White"></HeaderStyle>
</asp:GridView>
</div>
</asp:Panel>
</ContentTemplate>
</ajax:TabPanel>
</ajax:TabContainer>
==================
My C# code is
protected void GRVToppers_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
var dept = from n in ecme.DEPT_MASTER
select new { n.DEPT_ID, n.DEPT_NAME };
DropDownList ddl = null;
if (e.Row.RowType == DataControlRowType.Footer)
{
ddl = e.Row.FindControl("ddladdnewDeptname") as DropDownList;
int cnt = 0;
cnt = dept.Count();
ListItem[] items = new ListItem[cnt];
for (int i = 0; i < cnt; i++)
{
items[i] = new ListItem("DEPT_NAME", "DEPT_ID");
}
}
}
catch (Exception)
{ }
}
========================
You can do this very easily...
Remove
DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="True"
and
DataTextField='<%#Bind("DEPT_NAME") %>' DataValueField='<%#Bind("DEPT_ID") %>' AppendDataBoundItems="true"
from aspx code
and Make changes in
protected void GRVToppers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var dept = from n in ecme.DEPT_MASTER
select new { n.DEPT_ID, n.DEPT_NAME };
DropDownList ddl = (DropDownList)e.Row.FindControl("ddladdnewDeptname");
ddl.DataTextField = "DEPT_NAME";
ddl.DataValueField = "DEPT_ID";
ddl.DataSource = dept.ToList();
ddl.DataBind();
ddl.Items.Insert(0, "--Select Department--");
}
}
100% sure this 'll work...

I am getting null when I am using (DropDownList)e.Row.FindControl

Here is my code where it's giving the value of ddl = null:
//event handler to bind the data to the row before rendering the gridview
protected void gridview1_RowDataBound(object sender ,GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)&&(e.Row.DataItem!=null))
{
//DropDownList ddlNo = (DropDownList)e.Row.FindControl("ddlNo");
DropDownList ddlNo = (DropDownList)e.Row.FindControl("ddlNo");
if (ddlNo != null)
{
ddlNo.DataSource = Test.GetData();
ddlNo.DataBind();
ddlNo.SelectedValue = gridview1.DataKeys[e.Row.RowIndex].Values[0].ToString();//datakeys are used to retain the value of the no. in edit mode
}
}
}
Here is my aspx code:
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false" AutoGenerateDeleteButton="false" AutoGenerateEditButton="false" ShowFooter="true" EmptyDataText="No data available." PagerStyle-HorizontalAlign="Right" AllowPaging="true" AllowSorting="true" GridLines="Vertical" Width="98%" EnableViewState="true" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowDataBound="gridview1_RowDataBound" OnRowEditing="gridview1_RowEditing" OnRowUpdating="gridview1_RowUpdating" OnRowCommand="gridview1_RowCommand" OnRowDeleting="gridview1_RowDeleting" DataKeyNames="testID">
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblSelect" runat="server" Text="Select"></asp:Label>
<%-- <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckChanged" />--%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:BoundField DataField="testID" HeaderText="SearchId" />
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("testDesc") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("testDesc") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="No." HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="ddlNo" runat="server" DataTextField="testNo" DataValueField="testNo" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblNo" runat="server" Text='<%# Bind("testNo") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewNo" runat="server" DataTextField="testNo" DataValueField="testNo">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="linkbt1" runat="server" CausesValidation="true" CommandName="Update" Text="Update">
</asp:LinkButton>
<asp:LinkButton ID="linkbt2" runat="server" CausesValidation="false" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="linkbt1" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit">
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkbt2" runat="server" CausesValidation="false" CommandName="AddNew" Text="AddNew">
</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="true" ShowHeader="true" />
</Columns>
</asp:GridView>
Can anyone provide a relevant solution to this?
you put the ddl no in the footer template but you're only checking for that in the (e.Row.RowType == DataControlRowType.DataRow) Change that to FooterRow and it should find it
change the above line to
if(e.Row.RowType == DataControlRowType.Footer && e.Row.DataItem != null)
<%--DataKeyNames="Environment_ID"--%>
' />
<%--
'>
' />
--%>
' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblapp" runat="server" Text='<%# Eval("AppName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAppFooter" class="SearchBoxRTD" runat="server" DataTextField="AppName"
DataValueField="SNO">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TestType" HeaderStyle-Width="50">
<EditItemTemplate>
<asp:DropDownList ID="ddlTestTypeDataRow" class="SearchBoxRTD" runat="server" DataTextField="Testingtypedescription"
DataValueField="TestingTypeID">
</asp:DropDownList>
<asp:HiddenField ID="hdnTesttype" runat="server" Value='<%# Bind("Testtype") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTestType" runat="server" Text='<%# Eval("Testingtypedescription") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTestTypeFooter" class="SearchBoxRTD" runat="server" DataTextField="Testingtypedescription"
DataValueField="TestingTypeID">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Scenario Type" HeaderStyle-Width="50">
<EditItemTemplate>
<asp:DropDownList ID="ddlScenarioTypeDataRow" class="SearchBoxRTD" runat="server" DataTextField="ScenarioTypedescription"
DataValueField="ScenarioTypeID">
</asp:DropDownList>
<asp:HiddenField ID="hdnScenariotype" runat="server" Value='<%# Bind("ScenarioTypeID") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblScenarioType" runat="server" Text='<%# Eval("ScenarioTypedescription") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlScenarioTypeFooter" class="SearchBoxRTD" runat="server"
DataTextField="ScenarioTypedescription" DataValueField="ScenarioTypeID">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Scenario">
<EditItemTemplate>
<asp:TextBox ID="txtScenario" runat="server" Text='<%# Bind("Scenario") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RFDGEdUI" runat="server" Font-Bold="true" ErrorMessage="*"
ControlToValidate="txtScenario" ValidationGroup="EditScenario"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblScenario" runat="server" Text='<%# Bind("Scenario") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtfootScenario" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFDGScenario" runat="server" Font-Bold="true" ErrorMessage="*"
ControlToValidate="txtfootScenario" ValidationGroup="AddScenario"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<EditItemTemplate>
<asp:CheckBox ID="chkScenariostatus" runat="server" Checked='<%# Bind("Status") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblScenarioStatus" runat="server" Text='<%# Bind("Status") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkScenariofooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdateScenario" runat="server" ValidationGroup="EditScenario"
CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancelScenario" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAddScenario" runat="server" ValidationGroup="AddScenario"
CausesValidation="True" CommandName="Insert" Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEditScenario" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Applications available!
</EmptyDataTemplate>
</asp:GridView>
--------------------------------CS--------------------------------------------------------
protected void grdScenario_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DataSet ds = GetData("qtp_getservice");
if (e.Row.RowType == DataControlRowType.DataRow)
{
//services,environment,platform
// bool flag = false;
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
Label lbl = (Label)e.Row.FindControl("LblScenarioStatus");
if (null != lbl && lbl.Text != "")
{
lbl.Text = (string.Compare(lbl.Text, "True", true) == 0) ? "Enabled" : "Disabled";
}
}
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
// {
// for (int i = 0; i < grdScenario.Rows.Count ; i++)
// {
// foreach (GridViewRow gvRow in grdScenario.Rows)
{
DropDownList ddlApp = (DropDownList)e.Row.FindControl("ddlAppDataRow");
DropDownList ddlTT = (DropDownList)e.Row.FindControl("ddlTestTypeDataRow");
DropDownList ddlST = (DropDownList)e.Row.FindControl("ddlScenarioTypeDataRow");
//Label lblapp = ((Label)e.Row.Cells[2].FindControl("lblapp"));
//Label lblTestType = ((Label)e.Row.Cells[3].FindControl("lblTestType"));
//Label lblScenarioType = ((Label)e.Row.Cells[4].FindControl("lblScenarioType"));
// Label lblapp = ((Label)grdScenario.Rows[i].Cells[2].FindControl("lblapp"));
//Label lblTestType = ((Label)grdScenario.Rows[i].Cells[3].FindControl("lblTestType"));
// Label lblScenarioType = ((Label)grdScenario.Rows[i].Cells[4].FindControl("lblScenarioType"));
if (ddlApp != null)
{
HiddenField hdnAppid = (HiddenField)e.Row.FindControl("hdnAppid");
ddlApp.DataSource = ds.Tables[4].DefaultView;
ddlApp.DataTextField = "AppName";
ddlApp.DataValueField = "SNO";
ddlApp.DataBind();
//ddlApp.SelectedIndex = ddlApp.Items.IndexOf(ddlApp.Items.FindByText(grdScenario.DataKeys[e.Row.RowIndex].Values[1].ToString()));
//ddlApp.SelectedItem.Text = lblapp.Text.ToString();
ddlApp.SelectedValue = hdnAppid.Value;
}
if (ddlTT != null)
{
HiddenField hdnTesttype = (HiddenField)e.Row.FindControl("hdnTesttype");
ddlTT.DataSource = ds.Tables[5].DefaultView;
ddlTT.DataTextField = "Testingtypedescription";
ddlTT.DataValueField = "TestingTypeID";
ddlTT.DataBind();
//ddlTT.SelectedItem.Text = lblTestType.Text.ToString();
ddlTT.SelectedValue = hdnTesttype.Value;
//ddlTT.SelectedIndex = ddlTT.Items.IndexOf(ddlTT.Items.FindByText(grdservices.DataKeys[e.Row.RowIndex].Values[2].ToString()));
}
if (ddlST != null)
{
HiddenField hdnScenariotype = (HiddenField)e.Row.FindControl("hdnScenariotype");
ddlST.DataSource = ds.Tables[6].DefaultView;
ddlST.DataTextField = "ScenarioTypeDescription";
ddlST.DataValueField = "ScenarioTypeID";
ddlST.DataBind();
ddlST.SelectedValue = hdnScenariotype.Value;
//ddlST.SelectedItem.Text = lblScenarioType.Text.ToString();
//ddlST.SelectedIndex = ddlST.Items.IndexOf(ddlST.Items.FindByText(grdScenario.DataKeys[e.Row.RowIndex].Values[3].ToString()));
}
}
// }
//// }
}
if (e.Row.RowType == DataControlRowType.Footer)
{
//Bind environment,platform at footer.
DropDownList cmbNewType = (DropDownList)e.Row.FindControl("ddlAppFooter");
cmbNewType.DataSource = ds.Tables[4].DefaultView;
cmbNewType.DataBind();
DropDownList cmbNewType1 = (DropDownList)e.Row.FindControl("ddlTestTypeFooter");
cmbNewType1.DataSource = ds.Tables[5].DefaultView;
cmbNewType1.DataBind();
DropDownList cmbNewType2 = (DropDownList)e.Row.FindControl("ddlScenarioTypeFooter");
cmbNewType2.DataSource = ds.Tables[6].DefaultView;
cmbNewType2.DataBind();
}
}
catch (System.Exception) { }
}

Categories