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
Related
I use a CalendarExtender of AjaxControlToolkit in a GridView and a TextBox. And from that TextBox I want to disable future dates.
I am trying below code
<asp:GridView ID="Gridview2" runat="server" AutoGenerateColumns="false" DataKeyNames="Sno" ShowFooter="true" OnRowCommand="Gridview2_RowCommand" CssClass="table table-bordered table-striped"
OnRowCancelingEdit="Gridview2_RowCancelingEdit" OnRowDeleting="Gridview2_RowDeleting" OnRowEditing="Gridview2_RowEditing" OnRowUpdating="Gridview2_RowUpdating" OnRowDataBound="Gridview2_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Sno" Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_sno1" runat="server" Text='<%#Eval("Sno") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of visit" ShowHeader="false">
<EditItemTemplate>
<asp:TextBox ID="Txt_update_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' CssClass="form-control"/>
<cc1:CalendarExtender ID="CalendarExtenderedit11" CssClass="Calendar" TargetControlID="Txt_update_DateofVisit1" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbl_DateofVisit1" runat="server" Text='<%# Eval("DateofVisit","{0:MM/dd/yyyy}") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_DateofVisit_add" runat="server" CssClass="form-control" />
<cc1:CalendarExtender ID="CalendarExtendere21" CssClass="Calendar" TargetControlID="txt_DateofVisit_add" Format="MM/dd/yyyy" runat="server"></cc1:CalendarExtender>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgbtnDelete_add" runat="server" CommandName="Delete" ImageUrl="~/img/grid_delete.png" Text="Edit" ToolTip="click here to delete" />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd_add" runat="server" CommandName="AddNew" ImageUrl="~/img/grid_add.png" ToolTip="click here to add" CausesValidation="true" ValidationGroup="outadd" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Below is my RowDataBound
protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 = (AjaxControlToolkit.CalendarExtender)Gridview2.FooterRow.FindControl("CalendarExtendere21");
CalendarExtendere21.EndDate = DateTime.Now;
// CalendarExtendere21.StartDate = DateTime.Now;
}
}
I get below error:
Object reference not set to an instance of an object.
just use parameter e to find out control in grid
if (e.Row.RowType == DataControlRowType.Footer)
{
AjaxControlToolkit.CalendarExtender CalendarExtendere21 =
(e.Row.FindControl("CalendarExtendere21") as AjaxControlToolkit.CalendarExtender);
}
and don't forget to check for null
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.
All the examples I've found have not been helpful. I have a textbox in the footer of my gridview called "txtMyCoverage". In my codebehind I just want to reference that textbox to say
a = txtMyCoverage.Text;
I tried
gvLimit.FindControl("txtMyCoverage").ToString();
but it comes back null reference. Thanks for any help!
Here is my grid
<asp:GridView Width="100%" ID="gvLimits"
CssClass="gridView no_min_width"
runat="server"
AutoGenerateColumns="False"
CellPadding="2" ShowFooter="true"
DataKeyNames="PolicyLimitID, LimitID"
HorizontalAlign="Center"
OnRowDataBound="gvLimits_RowDataBound">
<RowStyle HorizontalAlign="Center" />
<Columns>
<asp:TemplateField HeaderText="Coverage">
<ItemTemplate>
<asp:Label ID="txtLimitLetter" runat="server" Width="20px" CssClass="center" Text='<%# Bind("Limit.LimitLetter") %>' Enabled="false" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtMyCoverage" runat="server" Width="50px" CssClass="center" ></asp:TextBox>
</FooterTemplate>
</Columns>
</asp:GridView>
if You Used TextBox Like this:
<asp:TemplateField HeaderText="Coverage">
<ItemTemplate>
<asp:Label ID="txtLimitLetter" runat="server" Width="20px" CssClass="center" Text='<%# Bind("Limit.LimitLetter") %>' Enabled="false" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtMyCoverage" runat="server" Width="50px" CssClass="center" ></asp:TextBox>
</FooterTemplate>
then it You can find On rowbound like this:
On RowBoundEvent of Grid
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TextBox txtLimitLetter=(TextBox)e.Row.FindControl("txtLimitLetter");
}
}
or
you can Look Through GridView Rows
foreach(GridViewRow row in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
TextBox txtLimitLetter=(TextBox)e.Row.FindControl("txtLimitLetter");
}
}
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) { }
}
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();
}
}
}