I am binding dynammic gridview and in which i need one column in which linkbutton created dynamically in row data bound,but when i am click button gridview is being disappear.How to solve it please give me proper solutions.
i am creating Dynammic link button on raw databound..
<asp:GridView ID="grdResult" runat="server" CssClass="table-grid" OnRowDataBound="grdResult_RowDataBound" OnRowCreated="grdResult_RowCreated" EnableViewState="false">
<EmptyDataTemplate>
<asp:Label ID="Label6" runat="server" Text="Record Not Found."></asp:Label>
</EmptyDataTemplate>
</div>
<div id="DivFooterRow" style="overflow: hidden">
</div>
<%-- <div class="row" style="text-align: center;">
Record Not Found.
</div>--%>
<div class="row" style="height: 30px; color: orangered;">
<div class="col-sm-2">
Verify & Check the Result?
</div>
<div class="col-sm-4">
<asp:CheckBox ID="chkForwardToFOR" runat="server" />
</div>
</div>
<asp:LinkButton ID="lnkbtnRemarks" runat="server"></asp:LinkButton>
<ajaxToolkit:ModalPopupExtender ID="mpeRemarks" runat="server" DropShadow="false" PopupControlID="pnlMessage"
TargetControlID="lnkbtnRemarks" BackgroundCssClass="modalBox_back">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="pnlMessage" runat="server" Style="display: none;" CssClass="modal-dialog2">
<asp:UpdatePanel ID="UpdatePanel12" runat="server">
<ContentTemplate>
<div class="modal-dialog" style="width: 600px;">
<div class="modal-content">
<div class="modal-header">
<asp:ImageButton ID="imgBtnClose" runat="server" class="close" ImageUrl="~/App_Themes/Images/cross.png" AlternateText="X" OnClick="imgBtnClose_Click" />
<h4 class="modal-title" id="myModalLabel1"><i class="fa fa-globe"></i>
Remarks</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-sm-12">
<asp:Label ID="lblremarks" runat="server"></asp:Label>
</div>
</div>
</div>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Laboratory_ResultUploadation : System.Web.UI.Page
{
String strConn = ConfigurationManager.ConnectionStrings["ConOrms"].ConnectionString;
String strConnString = ConfigurationManager.ConnectionStrings["xlsConstr"].ConnectionString;
String strConnStringXlsx = ConfigurationManager.ConnectionStrings["xlsxConstr"].ConnectionString;
private static string _BranchId;
private static string _YearID;
private static string _Year;
public static string BranchId { get { return _BranchId; } set { _BranchId = value; } }
public static string YearID { get { return _YearID; } set { _YearID = value; } }
public static string Year { get { return _Year; } set { _Year = value; } }
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//grdResult.DataBind();
BindDropDown();
GetUserByBranchID();
// BindTesult(dt);
//if (SessionManager.Instance.BranchId != null)
//{
// ddlBranch.SelectedValue = SessionManager.Instance.BranchId;
// if (SessionManager.Instance.RoleId != "6")
// {
// ddlBranch.Enabled = false;
// }
// else
// {
// ddlBranch.Enabled = true;
// }
//}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (ddlBranch.SelectedValue != "" && txtTRFNo.Text != "")
{
string FilesPath = string.Empty;
if (fuupload.HasFile)
{
try
{
string Extension = Path.GetExtension(fuupload.PostedFile.FileName);
if (Extension == ".xls" || Extension == ".xlsx")
{
FilesPath = Server.MapPath("~/DataExcel/") + Path.GetFileName(fuupload.PostedFile.FileName);
if (File.Exists(FilesPath))
{
File.Delete(FilesPath);
fuupload.SaveAs(FilesPath);
}
else
{
fuupload.SaveAs(FilesPath);
}
// GetExcelColumn(FilesPath);
Unpivot(FilesPath);
// grdResult.DataSource = null;
// grdResult.DataBind();
}
}
catch (Exception ex)
{
lblmsg.Text = "Internal Error. !!! Please try later.!";
lblmsg.Style.Add("color", "Red");
}
}
else
{
lblmsg.Text = "There is no file to upload !!";
lblmsg.Style.Add("color", "Red");
}
}
else
{
lblmsg.Text = "Please Select Branch and Trf No";
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
#region Autocomplete
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchTRF(string prefixText, int count)
{
// int LabId = BranchId;
List<string> Trflist = new List<string>();
string Item = string.Empty;
try
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConOrms"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Sp_GetTrfNo";
cmd.Parameters.Add("@BranchId", SqlDbType.Int).Value = int.Parse(Laboratory_ResultUploadation._BranchId);
cmd.Parameters.Add("@SearchText", SqlDbType.NVarChar).Value = prefixText;
cmd.Parameters.Add("@YearID", SqlDbType.Int).Value = int.Parse(Laboratory_ResultUploadation._YearID);
cmd.Parameters.Add("@Year", SqlDbType.NVarChar).Value = Laboratory_ResultUploadation._Year;
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Trflist.Add(dr["TRFNo"].ToString());
}
con.Close();
}
}
}
catch (Exception ex)
{
}
return Trflist;
}
#endregion
private void BindDropDown()
{
try
{
MasterEntry.BindDropDownEx(ddlBranch, DBProcedure.GetAllBranch, "BranchName", "BranchId", "Select Branch");
MasterEntry.BindDropDownEx(ddlYear, DBProcedure.GetAllYear, "Year", "YearID", "Select Year");
}
catch (Exception ex)
{
}
}
public string GetVirtualPath(string physicalPath)
{
if (!physicalPath.StartsWith(HttpContext.Current.Request.PhysicalApplicationPath))
{
throw new InvalidOperationException("Physical path is not within the application root");
}
return "~/" + physicalPath.Substring(HttpContext.Current.Request.PhysicalApplicationPath.Length)
.Replace("\\", "/");
}
#region Excel Upload
//private void GetExcelColumn(string strPath)
//{
// OleDbConnection connection = new OleDbConnection();
// try
// {
// string ConnectionString = string.Empty;
// string DocumentSavePath = string.Empty;
// string FileExtnsion = "." + strPath.Split('.').Last();
// DocumentSavePath = GetVirtualPath(strPath);
// if (FileExtnsion.ToUpper().ToString() == ".XLS")
// {
// ConnectionString = strConnString;
// }
// else if (FileExtnsion.ToUpper().ToString() == ".XLSX")
// {
// ConnectionString = strConnStringXlsx;
// }
// ConnectionString = string.Format(ConnectionString, HttpContext.Current.Server.MapPath(DocumentSavePath));
// DataTable dtExcel = new DataTable();
// if (dtExcel.Columns.Count == 0)
// {
// dtExcel.Columns.Add("UnitName", typeof(System.String));
// }
// connection = new OleDbConnection(ConnectionString);
// if (connection.State == ConnectionState.Closed)
// connection.Open();
// OleDbCommand objCmdSelect = new OleDbCommand();
// DataTable DtTemp = new DataTable();
// DataTable dbSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// if (dbSchema == null || dbSchema.Rows.Count < 1)
// {
// throw new Exception("Error: Could not determine the name of the first worksheet.");
// }
// string firstSheetName = "";
// if (FileExtnsion.ToUpper().ToString() == ".XLS" || FileExtnsion.ToUpper().ToString() == ".XLSX")
// {
// foreach (DataRow dr in dbSchema.Rows)
// {
// firstSheetName = dr["TABLE_NAME"].ToString();
// if (firstSheetName[firstSheetName.Length - 1] != '$')
// {
// firstSheetName = firstSheetName + "$";
// }
// break;
// }
// }
// else
// {
// firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
// }
// DataTable Dt = new DataTable();
// objCmdSelect = new OleDbCommand("SELECT * FROM [" + firstSheetName + "]", connection);
// OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmdSelect);
// objAdapter.Fill(Dt);
// int TotalCount = 0;
// if (Dt.Columns.Count >= 0)
// {
// foreach (DataRow dr in Dt.Rows)
// {
// DataRow drExcel = dtExcel.NewRow();
// if (dr[1].ToString().Trim() != string.Empty)
// {
// drExcel["UnitName"] = dr[1].ToString().Trim();
// dtExcel.Rows.Add(drExcel);
// TotalCount++;
// }
// }
// }
// if (dtExcel.Rows.Count > 0)
// {
// try
// {
// using (SqlConnection con = new SqlConnection(strConn))
// {
// using (SqlCommand cmd = new SqlCommand())
// {
// cmd.CommandType = CommandType.StoredProcedure;
// cmd.CommandText = "InsertUnitFromExcel";
// cmd.Parameters.Add("@TypeTabl", SqlDbType.Structured).Value = dtExcel;
// cmd.Parameters.Add("@retval", SqlDbType.Int).Value = 0;
// cmd.Parameters["@retval"].Direction = ParameterDirection.InputOutput;
// cmd.Parameters.Add("@Count", SqlDbType.Int).Value = 0;
// cmd.Parameters["@Count"].Direction = ParameterDirection.InputOutput;
// cmd.Connection = con;
// con.Open();
// cmd.ExecuteNonQuery();
// if (cmd.Parameters["@retval"].Value.ToString() == "1")
// {
// // getData(Convert.ToInt32(ViewState["PageNumDraft"]));
// int Icount = Convert.ToInt16(cmd.Parameters["@Count"].Value.ToString());
// int RestUnit = Convert.ToInt16(TotalCount - Icount);
// lblmsg.ForeColor = System.Drawing.Color.Green;
// //// lblmsg.Text = "successfully Saved " + "(" + Icount + "/" + TotalCount + ")";
// //lblrestcountmsg.Visible = true;
// if (RestUnit > 1)
// {
// // lblrestcountmsg.Text = " Rest " + RestUnit + " Units are duplicate";
// // lblrestcountmsg.Style.Add("color", "red");
// }
// else if (RestUnit == 1)
// {
// // lblrestcountmsg.Text = " Rest " + RestUnit + " Unit is duplicate";
// // lblrestcountmsg.Style.Add("color", "red");
// }
// else
// {
// // lblrestcountmsg.Text = " No One Unit is duplicate";
// // lblrestcountmsg.Style.Add("color", "green");
// }
// }
// }
// }
// }
// catch (Exception ex)
// {
// lblmsg.ForeColor = System.Drawing.Color.Red;
// lblmsg.Text = "Error: Message :" + ex.Message;
// }
// }
// else
// {
// lblmsg.ForeColor = System.Drawing.Color.Red;
// lblmsg.Text = "There is no rows found in this Excel sheet !! ";
// }
// }
// catch (Exception ex)
// {
// lblmsg.ForeColor = System.Drawing.Color.Red;
// lblmsg.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
// }
// finally
// {
// if (connection.State == ConnectionState.Open)
// connection.Close();
// }
//}
#endregion
#region UNPIVOT
private void Unpivot(string strPath)
{
OleDbConnection connection = new OleDbConnection();
try
{
string ConnectionString = string.Empty;
string DocumentSavePath = string.Empty;
string FileExtnsion = "." + strPath.Split('.').Last();
DocumentSavePath = GetVirtualPath(strPath);
if (FileExtnsion.ToUpper().ToString() == ".XLS")
{
ConnectionString = strConnString;
}
else if (FileExtnsion.ToUpper().ToString() == ".XLSX")
{
ConnectionString = strConnStringXlsx;
}
ConnectionString = string.Format(ConnectionString, HttpContext.Current.Server.MapPath(DocumentSavePath));
connection = new OleDbConnection(ConnectionString);
if (connection.State == ConnectionState.Closed)
connection.Open();
OleDbCommand objCmdSelect = new OleDbCommand();
DataTable DtTemp = new DataTable();
DataTable dbSchema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = "";
if (FileExtnsion.ToUpper().ToString() == ".XLS" || FileExtnsion.ToUpper().ToString() == ".XLSX")
{
foreach (DataRow dr in dbSchema.Rows)
{
firstSheetName = dr["TABLE_NAME"].ToString();
if (firstSheetName[firstSheetName.Length - 1] != '$')
{
firstSheetName = firstSheetName + "$";
}
break;
}
}
else
{
firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
}
DataTable Dt = new DataTable();
objCmdSelect = new OleDbCommand("SELECT * FROM [" + firstSheetName + "]", connection);
OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmdSelect);
DataTable dtExcel = new DataTable();
DataTable dtClone = new DataTable();
if (dtExcel.Columns.Count == 0)
{
dtExcel.Columns.Add("LabID", typeof(System.String));
dtExcel.Columns.Add("TRFID", typeof(System.String));
dtExcel.Columns.Add("SampleCode", typeof(System.String));
dtExcel.Columns.Add("Parameter", typeof(System.String));
dtExcel.Columns.Add("Unit", typeof(System.String));
dtExcel.Columns.Add("Chemist", typeof(System.String));
dtExcel.Columns.Add("Result", typeof(System.String));
}
objAdapter.Fill(Dt);
if (Dt.Columns.Count >= 0)
{
string[] columnNames = Dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
for (int i = 2; i < Dt.Rows.Count; i++)
{
for (int j = 0; j < Dt.Columns.Count; j++)
{
DataRow drExcel = dtExcel.NewRow();
drExcel["LabID"] = ddlBranch.SelectedValue.ToString();
drExcel["TRFID"] = txtTRFNo.Text.Trim();
drExcel["SampleCode"] = Dt.Rows[i]["Lab Code"].ToString().Trim();
drExcel["Parameter"] = Dt.Columns[j].ColumnName.ToString().Trim();
drExcel["Unit"] = Dt.Rows[0][Dt.Columns[j].ColumnName].ToString().Trim();
drExcel["Chemist"] = Dt.Rows[1][Dt.Columns[j].ColumnName].ToString().Trim();
drExcel["Result"] = Dt.Rows[i][Dt.Columns[j].ColumnName].ToString().Trim();
dtExcel.Rows.Add(drExcel);
}
}
dtExcel = dtExcel.AsEnumerable()
.Where(r => r.Field<string>("Parameter") != "Lab Code")
.CopyToDataTable();
dt = dtExcel;
BindTesult(dt);
//if (dtExcel.Rows.Count > 0)
//{
// try
// {
// using (SqlConnection con = new SqlConnection(strConn))
// {
// dt = new DataTable();
// using (SqlCommand cmd = new SqlCommand("SP_TestResult_upload_validation", con))
// {
// cmd.CommandType = CommandType.StoredProcedure;
// cmd.Parameters.Add("@par", SqlDbType.Structured).Value = dtExcel;
// cmd.Parameters.Add("@ReturnVal", SqlDbType.NVarChar, 200).Value = "";
// cmd.Parameters["@ReturnVal"].Direction = ParameterDirection.InputOutput;
// cmd.CommandTimeout = 0;
// SqlDataAdapter adp = new SqlDataAdapter(cmd);
// adp.Fill(dt);
// if (dt.Columns.Contains("ID"))
// dt.Columns.Remove("ID");
// BindTesult(dtExcel);
// lblmsg.ForeColor = System.Drawing.Color.Red;
// lblmsg.Text = cmd.Parameters["@ReturnVal"].Value.ToString();
// }
// }
// }
// catch (Exception ex)
// {
// lblmsg.ForeColor = System.Drawing.Color.Red;
// lblmsg.Text = "Error: Message :" + ex.Message;
// }
//}
}
else
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "There is no rows found in this Excel sheet !! ";
}
}
catch (Exception ex)
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
finally
{
if (connection.State == ConnectionState.Open)
connection.Close();
}
}
#endregion
protected void ddlBranch_SelectedIndexChanged(object sender, EventArgs e)
{
txtTRFNo.Text = string.Empty;
Laboratory_ResultUploadation.BranchId = ddlBranch.SelectedValue;
}
private void BindTesult(DataTable dtreport)
{
if (dtreport.Rows.Count > 0)
{
grdResult.DataSource = dtreport;
grdResult.DataBind();
}
else
{
grdResult.DataSource = null;
grdResult.DataBind();
}
}
private void GetUserByBranchID()
{
DataTable dtUser = MasterEntry.GetUserByBranchID(Convert.ToInt32(SessionManager.Instance.BranchId), Convert.ToInt16(SessionManager.Instance.RoleId));
ddlReceivedby.DataSource = dtUser;
ddlReceivedby.DataTextField = "Name";
ddlReceivedby.DataValueField = "UserId";
ddlReceivedby.DataBind();
ddlReceivedby.Items.Insert(0, new ListItem("-- Select Received By --", "0"));
ddlAlotter.DataSource = dtUser;
ddlAlotter.DataTextField = "Name";
ddlAlotter.DataValueField = "UserId";
ddlAlotter.DataBind();
ddlAlotter.Items.Insert(0, new ListItem("-- Select Alotter --", "0"));
}
protected void txtTRFNo_TextChanged(object sender, EventArgs e)
{
if (txtTRFNo.Text != string.Empty)
{
try
{
string[] FindValue = txtTRFNo.Text.Trim().Split(';');
if (FindValue.Length >= 2)
{
txtTRFNo.Text = FindValue[0].ToString();
BindAllSampleCode(FindValue[0].ToString());
}
else
{
txtTRFNo.Text = string.Empty;
}
}
catch (Exception ex)
{
}
}
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
txtTRFNo.Text = string.Empty;
Laboratory_ResultUploadation.YearID = ddlYear.SelectedValue;
Laboratory_ResultUploadation.Year = Convert.ToString(ddlYear.SelectedItem);
}
private void BindAllSampleCode(string TrfNo)
{
DataTable dtsampleCode = new DataTable();
dtsampleCode = MasterEntry.GetAllSampleCode(TrfNo);
if (dtsampleCode.Rows.Count > 0)
{
txtSamplesCodeAre.Text = Convert.ToString(dtsampleCode.Rows[0]["AllSampleCode"].ToString());
}
else
{
txtSamplesCodeAre.Text = string.Empty;
}
}
protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int J = e.Row.RowIndex + 1;
for (int i = 0; i < dt.Columns.Count; i++)
{
ImageButton imgbtn = new ImageButton();
Label lbl = new Label();
HiddenField hdnRemarks = new HiddenField();
if (i == (dt.Columns.Count - 1) && J > 2)
{
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Attributes.Add("runat", "server");
lnkView.Click += ViewDetails;
lnkView.CommandArgument = dt.Rows[J - 1][dt.Columns[i].ColumnName.ToString()].ToString();
e.Row.Cells[i].Controls.Add(lnkView);
}
else
{
lbl.ID = "lbl" + i;
e.Row.Cells[i].Controls.Add(lbl);
lbl.Text = dt.Rows[J - 1][dt.Columns[i].ColumnName.ToString()].ToString();
}
}
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[0].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
//protected void Page_Init(object sender, EventArgs e)
//{
// grdResult.DataBind();
//}
protected void grdResult_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//int J = e.Row.RowIndex + 1;
//for (int i = 1; i < e.Row.Cells.Count; i++)
//{
// ImageButton imgbtn = new ImageButton();
// Label lbl = new Label();
// HiddenField hdnRemarks = new HiddenField();
// if (i == e.Row.Cells.Count && i > 2)
// {
// //imgbtn.ID = "imgbtn" + i;
// //imgbtn.CommandName = "viewremarks";
// //// imgbtn.Command += LinkButton_Command;
// //imgbtn.CommandArgument = "1";
// //e.Row.Cells[i].Controls.Add(imgbtn);
// //imgbtn.Height = 15;
// //imgbtn.Width = 15;
// //imgbtn.ImageUrl = "~/App_Themes/Images/magnifier-1.png";
// //hdnRemarks.ID = "hdnRemarks" + i;
// //e.Row.Cells[i].Controls.Add(hdnRemarks);
// }
// else
// {
// lbl.ID = "lbl" + i;
// e.Row.Cells[i].Controls.Add(lbl);
// lbl.Text = Convert.ToString(J);
// }
//}
}
}
protected void LinkButton_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "viewremarks")
{
}
}
protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "viewremarks")
{
// GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
}
}
protected void imgBtnClose_Click(object sender, ImageClickEventArgs e)
{
}
}