Good day everyone, I've a problem with the published web app when posting it at azure
so, my code is like 2 pages, one for the datalist, the other one is for input page
the problematic page is containing a gridview with a templatefield that contains 2 image buttons
one is for display block another div and fills the grid within
the other one is for redirect to input page with some session update for flagging the transaction is either new or editing
the problem is, my gridview_rowcommand method is working locally either on quick debugging (IIS Express) or run it via IIS
but when I publish it at azure, the rowcommand not functioning at all
below are some codes
<div class="divWrapperGrid" style="border-top:none;">
<div class="divContentGrid" style="min-height:190px;">
<asp:Button ID="btnChange" runat="server" Text="Button" Style="display:none;" OnClick="btnChange_Click"/>
<asp:UpdatePanel runat="server" ID="upWHOrder">
<ContentTemplate>
<asp:GridView ID="dgWHOrder" runat="server" AutoGenerateColumns="false" AllowPaging="true" ShowHeaderWhenEmpty="true"
CssClass="data-grid" HeaderStyle-CssClass="data-grid-header" RowStyle-CssClass="data-grid-row" EmptyDataRowStyle-CssClass="data-grid"
GridLines="None" EmptyDataText="There is no data"
OnRowDataBound ="dgWHOrder_RowDataBound" OnRowCommand="dgWHOrder_RowCommand">
<EmptyDataTemplate>
<asp:Label ID="Label2" CssClass="no-data-grid" runat="server">No records found!</asp:Label>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderStyle-CssClass="hidden-column" ItemStyle-CssClass="hidden-column">
<EditItemTemplate>
<asp:Label ID="laID" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="laID" runat="server" Text='<%#Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="WarehouseOrderNo" />
<asp:BoundField DataField="OrderDateStr" />
<asp:BoundField DataField="TotalItem" />
<asp:BoundField DataField="Responsible" />
<asp:BoundField DataField="MerchantCode" />
<asp:TemplateField ItemStyle-Width="35%" ItemStyle-HorizontalAlign="Right">
<EditItemTemplate>
<asp:ImageButton ID="btnSave" runat="server" CommandName="save" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/save-icon.png" Width="20px" Height="20px" ToolTip="Save" OnClientClick="return true;" />
<asp:ImageButton ID="btnCancel" runat="server" CommandName="cancel" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/cancel-icon.png" Width="20px" Height="20px" ToolTip="Cancel" OnClientClick="return true;" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" CommandName="edit" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/edit-icon.png" Width="20px" Height="20px" ToolTip="Update" OnClientClick="return true;" />
<asp:ImageButton ID="btnView" runat="server" CommandName="view" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" ImageUrl="~/images/delete-xxl.png" Width="20px" Height="20px" ToolTip="View" OnClientClick="return true;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
btnEdit is the redirect processing one
btnView is for the view processing one
and the gridview_rowcommand method
protected void dgWHOrder_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = 0;
rowIndex = Convert.ToInt32(e.CommandArgument);
string script = string.Empty;
int HeaderID = 0;
if (rowIndex > -1)
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
HeaderID = Convert.ToInt32(((Label)row.FindControl("laID")).Text);
}
BPWarehouseOrder objBP = new BPWarehouseOrder();
BOSearch objSrc = new BOSearch();
switch (e.CommandName)
{
case "edit":
IsEdit = true;
EditItemHeader = (from a in ListHeader
where a.ID == HeaderID
select a).Single();
Response.Redirect("WarehouseOrderIns.aspx");
break;
case "view":
List<BOWarehouseOrderDatail> objDt = new List<BOWarehouseOrderDatail>();
objBP = new BPWarehouseOrder();
objSrc = new BOSearch();
objSrc.FieldName = "IDWarehouseOrder";
objSrc.FieldValue = HeaderID.ToString();
objSrc.SearchType = "Equal";
objDt = objBP.GetDetailList(objSrc);
if (objBP.MsgCode != 0)
{
script += " alert('" + objBP.MsgDesc + #"');
";
ScriptManager.RegisterClientScriptBlock(this, GetType(), Guid.NewGuid().ToString(), script, true);
return;
}
dgOrderDetail.DataSource = objDt;
if (objDt.Count > 0)
{
dgOrderDetail.PageSize = objDt.Count;
}
dgOrderDetail.DataBind();
script += #" document.getElementById('popup').style.display = 'block';
";
ScriptManager.RegisterClientScriptBlock(this, GetType(), Guid.NewGuid().ToString(), script, true);
break;
}
}
TLDR: publishing website at azure, gridview_rowcommand function not working at azure, but working at local
Regards
Mediocre Programmer
I create the following sample using ASP.NET GridView control inside a UpdatePanel control, it works fine on my Azure web app service, OnRowCommand of the GridView control can be executed as expected.
GridView inside UpdatePanel
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="my_testgrid" runat="server" AutoGenerateColumns="false" OnRowCommand="my_testgrid_RowCommand">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("ID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="select" CommandName="select" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Specify data source in Page_Load event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("u001", "jack");
dt.Rows.Add("u002", "fred");
my_testgrid.DataSource = dt;
my_testgrid.DataBind();
}
}
OnRowCommand event
protected void my_testgrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
string arg = e.CommandArgument.ToString();
}
}
Browse the web app
OnRowCommand event can be executed if click [select] button
To troubleshot the issue, you can try to remote debug your web app and check if something wrong with your code.
Related
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.
I am making a reservation system and currently stuck on the following situation.
Basically I have a GridView which is loaded with the reservation ID and two LinkButton which opens a modal popup to enable the customer to view the details.
What I want to achieve is that when I click any LinkButton, it will show the ID from the first cell of a GridViewRow.
I have tried these methods here, here, here, and here but it still doesn't work. Is there any way to do it, Aside from using a SELECT Command and does involve async postback or if async postback is not possible with this, any fix recommended?
Here is my GridView code:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvReservationSummaries"/>
</Triggers>
<ContentTemplate>
<h2>Reservations</h2>
<br />
<asp:GridView ID="gvReservationSummaries" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" ShowHeader="False" CellPadding="5" CellSpacing="5"
onrowcommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%# Eval("Master_Reservation_ID")%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReservationDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Reservation Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReceiptDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Receipt Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9E4ABD_GratchiOBRSConnectionString2 %>"
SelectCommand="SELECT [Master_Reservation_ID] FROM [Master_Reservation] WHERE User_Unique_ID = #uuid">
<SelectParameters>
<asp:SessionParameter Name="uuid" SessionField="uid" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnShowModal" runat="server" Text="Show Modal 1 (Debug Purposes Only)" onclick="btnShowModal_Click" />
<!--Here, put the details of the reservaton, plus options to edit reservation.-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<asp:Panel ID="reservationSummaryModal" runat="server" Width="500px" Height="500px" style="display: none; background-color:Black; color:#CCC;">
<asp:Button ID="btnExitRs" runat="server" Text="Hide Modal (Debug Purposes Only)" onclick="btnExitAct_Click" />
<asp:Label ID="lblReservationSummary" runat="server" Text="Label"></asp:Label>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="HiddenField1" PopupControlID="reservationSummaryModal" BackgroundCssClass="modalBg" CancelControlID="btnExitRs">
</asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField1" runat="server" />
And here is my codebehind:
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewReservationDetails")
{
//GridViewRow gvr = gvReservationSummaries.Rows[Convert.ToInt32(e.CommandArgument)];
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else if (e.CommandName == "ViewReceiptDetails")
{
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else
{
}
}
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 having a nested update panel
something like this
<asp:UpdatePanel ID="DetailsUpdatePanel" runat="server" Visible="false" UpdateMode="Conditional" >
<ContentTemplate>
<div><ajaxToolkit:AsyncFileUpload runat="server" ID="BrochureUpload" Width="400px"
OnClientUploadError="BrochureuploadError"
OnClientUploadStarted="BrochureStartUpload"
OnClientUploadComplete="BrochureUploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red" ClientIDMode="AutoID"
ThrobberID="Throbber"
UploadingBackColor="#66CCFF"
onuploadedcomplete="BrochureUpload_UploadedComplete"/>
<asp:Label ID="Label1" runat="server" Style="display: none">
<asp:Image runat="server" ID="Image1" ImageUrl="~/Images/uploading.gif" />
</asp:Label>
<asp:Label ID="brochurelblstatus" runat="server" Style="font-family: Arial; font-size: small;"></asp:Label></div>
<div><asp:UpdatePanel runat="server" ID="child" UpdateMode="Conditional" >
<ContentTemplate>
<div>
<asp:GridView ID=GridView2" runat="server" AllowPaging="true" AutoGenerateColumns="false" CellPadding="0" CellSpacing="1" DataKeyNames="ArticleId">
<Columns>
<asp:BoundField DataField="ArticleId" HeaderText="ArticleId" ReadOnly="True" HeaderStyle-CssClass="td1" />
<asp:BoundField DataField="FileName" HeaderText="FileName" ReadOnly="True" HeaderStyle-CssClass="td2" />
<asp:TemplateField HeaderText="BrochureUrl">
<ItemTemplate>
<asp:HyperLink ID="lnkEPhoto" runat="server" BorderWidth="2px" NavigateUrl='<%# GetUrl(Eval("ArticleId"),Eval("FileName")) %>'
Target="_blank"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnRemove" runat="server" text="Delete" CommandName="Delete" CausesValidation="False" OnClientClick="DeleteOrNo()">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel></div>
</ContentTemplate>
</updatePanel>
CodeBehind:
protected void BrochureUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
if(BrochureUpload.HasFile)
{
if(BrochureUpload.PostedFile.ContentLength<=3670016 )
{
var brochurePath = MapPath("~/") + Path.GetFileName(e.filename);
BrochureUpload.SaveAs(brochurePath);
using (var dataContext = new NewsStandAloneDataContext(Config.StandaloneNewsConnectionString))
{
var brochure = new xxx
{
Id = Convert.ToInt32(GridView1.SelectedValue),
FileName = Path.GetFileName(e.filename),
RecordCreated = DateTime.Now
};
dataContext.xxx.InsertOnSubmit(brochure);
dataContext.SubmitChanges();
}
bindGridView();//I have code to bind gridview
Child.Update();
}
}
}
protected void bindBrochureGridView()
{
using (var dataContext = new NewsStandAloneDataContext(Config.StandaloneNewsConnectionString))
{
var brochureList = (from brochure in dataContext.xxx
where brochure.ArticleId == Convert.ToInt32(GridView2.SelectedValue)
select new ArcticleBrochure
{
ArticleId = brochure.ArticleId.ToString(),
FileName = brochure.FileName
}).ToList();
GridView1.DataSource = brochureList;
GridView1.DataBind();
}
}
When I upload the file , I want the giedview which is in the child updatepanel to be updated .But it doesnt work Any ideas?????
thanks in advance
Call child.Update(); in BrochureUpload_UploadedComplete event.
protected void BrochureUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
....................
....................
bindGridView();//I have code to bind gridview
child.Update();
}
When file upload is complete then call Child.Update() method of UpdatePanel which contain gridview. You need to do that because you set UpdateMode="Conditional" in this case you have to manually update it in code.
ChildrenAsTriggers="True" in your updatepanel.
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();
}
}
}