Read gridview cell values and text - c#

I am using the below code to read gridview controls value or text. But it return null value. I can't find out. But the gridview having some record with the value. Please help me to solve this.
GridViewRow row = null;
for (int i = 0; i < grd.Rows.Count; i++)
{
row = grd.Rows[i];
HiddenField file_id = (HiddenField)row.FindControl("FLD_ID");
Label pack_name = (Label)row.FindControl("FLD_NAME");
string text = file_id.Value;
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (isChecked)
{
//Here its comming
}
}
My partial gridview code here
<asp:GridView ID="grd" runat="server" BackColor="#CCCCCC" BorderColor="#93afba"
BorderStyle="Solid" BorderWidth="1px" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" PageSize="50" Width="100%" CellSpacing="2" ForeColor="#93afba"
Font-Size="14px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<%--<asp:CheckBox ID="chkall" runat="server" OnChange="checkAll();" />--%>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="FLD_ID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="lbl_id" runat="server" Value='<%#Bind("FLD_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbl_packname" runat="server" Text='<%#Bind("FLD_NAME") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>

i think you want to find Checkbox2 and you are finding chkSelect
please replace this
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
with
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)grd_proforma_bill.HeaderRow.FindControl("Checkbox2")).Checked;

your code is fine.
if you are binding gridview on page load be sure your code is as below block
if (!IsPostBack)
{
//code to bind gridview
}

Change the code to and check:
for (int i = 0; i < grd_proforma_bill.Rows.Count; i++)
{
HiddenField file_id = (HiddenField)grd_proforma_bill.Rows[i].FindControl("lbl_id");
Label pack_name = (Label)grd_proforma_bill.Rows[i].FindControl("lbl_packname");
string text = file_id.Value;
CheckBox cb = (CheckBox)grd_proforma_bill.Rows[i].FindControl("Checkbox2");
bool isChecked = cb.Checked;
if (isChecked)
{
//Here its comming
}
}

Related

Cell Text Always &nbsp:

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

GridView with SortExpression in column - I can't read the HeaderRow to make an Excel file with EPPlus - C Sharp C#

I' ve got an issue with my program.
When i do this:
GridView gvw = this.ProduttoriList1.FindControl("GridViewList") as GridView;
SqlDataSource dataSource = this.ProduttoriList1.FindControl(gvw.DataSourceID) as SqlDataSource;
FileInfo tempXlsFile = new FileInfo(HttpRuntime.CodegenDir + "\\" + Guid.NewGuid() + ".xlsx");
string filename = string.Format("Produttori_{0}.xlsx", Guid.NewGuid().ToString());
try
{
gvw.AllowPaging = false;
gvw.DataSourceID = string.Empty;
gvw.DataSource = dataSource;
gvw.DataBind();
//...some export commands with EPPlus...
}
catch (Exception exception)
{
throw exception;
}
finally
{
System.IO.File.Delete(tempXlsFile.ToString());
}
and i'm going to read the HeaderRow, i can't read the column that has a SortExpression (return a "" value).
<asp:Panel ID="Panel2" runat="server" Style="padding-top: 10px">
<asp:GridView ID="GridViewList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceList"
Width="100%" AllowPaging="True" AllowSorting="True" SkinID="GridViewDefault"
DataKeyNames="id">
<Columns>
<asp:TemplateField HeaderStyle-Width="30px" HeaderText="N°">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>.
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DescrLongITA" HeaderText="Produttore" SortExpression="DescrLongITA" />
<asp:TemplateField HeaderText="Modifica">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonEdit" runat="server" ImageUrl="~/Images/Icons/modifica.gif"
CommandArgument='<%# Eval("ID") %>' OnClick="ImageButtonEdit_Click" />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Elimina">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Icons/elimina.gif"
OnClientClick="return confirm("Continuare la cancellazione?")" CommandArgument='<%# Eval("ID") %>'
OnClick="ImageButtonDelete_Click" />
</ItemTemplate>
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<div style="color: #FF0000; padding: 30px">
<asp:Label ID="LabelEmpty1" runat="server" Text="Nessun dato trovato"></asp:Label>
</div>
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
In this case, i can't read the BoundField with HeaderText = "Produttore".
How can i do?
I found the solution, i hope to help you.
When I perform the preliminary steps of the export procedure and do this..
string[] columns = new string[gv.HeaderRow.Cells.Count];
for (int i = 0; i < columns.Length; i++)
{
columns[i] = gv.HeaderRow.Cells[i].Text;
}
Export(tmpFile, gv, columns);
i've replaced this one
columns[i] = gv.HeaderRow.Cells[i].Text;
with this one
var headertext = gv.Columns[i].HeaderText;
columns[i] = new DataColumn(headertext).ToString();

Image upload not working Always get the FALSE value

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

finding label in itemTemplate and bind data from code behind

I wanted to display value in a label (label inside itemTemplate)
i have tried this approach
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
string LabelText = ((Label)row.FindControl("labelSelf")).Text;
LabelText = s;
Response.Write(LabelText+"test");
}
}
but nothing is shown in the label inside the gridview. IT should display the value of s.
Next approach was
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
Label labelSelfCollect = GridView1.FindControl("labelSelf") as Label;
labelSelfCollect.Text = "Self Collect at "+ s;
I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
and the last approach that i have used is
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label labelcollect = row.FindControl("labelSelf") as Label;
labelcollect.Text = "self collect at "+ s;
}
}
}
using this method also it shows nothing.How should i assign the s value into this labelSelf(label inside itemTemplate)?
my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="772px" style="margin-left: 120px; text-align: left" Height="100px" DataKeyNames ="progressID" OnRowDataBound="GridView1_OnRowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" CssClass="rounded_corners" HeaderStyle-Height="40px">
<AlternatingRowStyle CssClass="rounded_corners tr tr" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="60" DataField="dateupdate" HeaderText="Date Update" DataFormatString="{0:dd/MM/yyyy}" >
<ControlStyle BorderWidth="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Progress">
<ItemTemplate >
<%# Eval("message") %>
<br />
<asp:label ID="labelRemark" runat="server" style="Font-Size:11.5px;" text='<%# Eval("remark") %>'></asp:label><br />
<asp:Label ID="labelSelf" runat="server" style="Font-Size:11.5px;" ></asp:Label><br />
<div id="div<%# Eval("progressID") %>" >
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="progressID" style="text-align:center; font-size:small;" CellPadding="4" OnRowCommand="GridView2_RowCommand" GridLines="None" CssClass="rounded_corners" Width="500px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="tackingNo" HeaderText="Courier Tracking No" ItemStyle-Font-Size="Small" ItemStyle-Width="150px" >
</asp:BoundField>
<asp:BoundField DataField="courierDate" HeaderText="Courier Date">
</asp:BoundField>
<asp:TemplateField HeaderText="Provider">
<ItemTemplate>
<asp:HyperLink Text='<%#Eval("providernm")%>' Target="_blank" runat="server" DataNavigateUrlFields="companyurl" NavigateUrl='<%#Eval("companyurl")%>' ></asp:HyperLink>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tracking" >
<ItemTemplate>
<br />
<asp:HyperLink Text="Track Here" Target="_blank" runat="server" DataNavigateUrlFields="trackingurl" NavigateUrl='<%#Eval("trackingurl")%>' ></asp:HyperLink>
<br />
<asp:Label ID="Label4" runat="server" Text="* check after 24 hours" Font-Italic="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonDELETE" runat="server" CommandName="Delete" Text="Delete" OnClientClick= "return confirm('Confirm Delete progress?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thank you.
Use GridView1_OnRowDataBound instead of foreach (GridViewRow row in GridView1.Rows). Apart from that your first approach is correct. You're simply not assigning the Text property there but reading from it.
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label labelSelf = (Label)e.Row.FindControl("labelSelf");
labelSelf.Text = address.getSelfCollectAddress(orderNoTracking); // maybe you need to retrieve the orderNoTracking from another control in this row or from it's datasource
}
}

Get the id of selected checkboxes in gridview (Asp.net) c#

I have two columns one for id & other for checkboxes.
i have taken checkboxes inside the gridview.
i wanted to see the checked values inside the gridview , If checkboxes are checked then i want those values i.e id
Asp.net
foreach(Gridviewrow gvr in Gridview1.Rows)
{
if(((CheckBox)gvr.findcontrol("CheckBox1")).Checked == true)
{
int uPrimaryid= gvr.cells["uPrimaryID"];
}
}
What you will have to do is use a template field:
<asp:TemplateField HeaderText="Field">
<ItemTemplate>
<div style="display: block">
<asp:Checkbox Checked='<%# DataBinder.Eval(Container.DataItem,"Field") %>'
runat="server" ID="chkField"></asp:Label>
</div>
</ItemTemplate>
</asp:TemplateField>
Then you can do:
foreach (DataGridRow dr in DataGrid1.Rows)
{
((CheckBox)gvr.FindControl("chkField")).Checked
}
to see if it's checked
in your aspx you have the following
<asp:GridView ID="gridViewID" runat="server" DataKeyNames="DataKey1,DataKey2,DataKey3" >
<Columns>
<asp:TemplateField HeaderText="selected">
<ItemTemplate>
<asp:CheckBox ID="checkBoxID" runat="server"
Checked='<%# Bind("Selected") %>'
OnCheckedChanged="checkBoxID_CheckedChanged"
AccessKey='<%# Container.DataItemIndex %>'
AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your event handler you do something similar to this:
protected void checkBoxID_CheckedChanged(object sender, EventArgs e)
{
var checkbox = (CheckBox)sender;
var rowIndex = Convert.ToInt32(checkbox.AccessKey);
var gridView = GetErhebungModulGridView();
var dataKey = gridView.DataKeys[rowIndex];
if (dataKey != null)
{
var dataKey1 = dataKey["DataKey1"];
var dataKey2 = dataKey["DataKey2"];
var dataKey3 = dataKey["DataKey3"];
//Do something with the variables keys above
}
}
<asp:gridview id="gv" runat="server">
<columns>
<asP:TemplateField>
<Asp:checkbox id="chk" runat="server" />
<Asp:literal id="ltlID" runat="server" visible="false" text='<%#eval("ID")%>' />
</asp:TemplateField>
</columns>
</asp:gridview>
For each row as gridviewrow in gv.rows
if ctype(row.findcontrol("chk"),checkbox).checked then
Dim _ID as integer = ctype(row.findcontrol("ltlID"),literal).text
end if
next

Categories