I am trying to refresh the datatablewith new content after click the button but it again shows the previous values also. I tried clear() but it doesn't work for me
protected void btnListItems_Click(object sender, EventArgs e)
{
lblMessage.Visible = false;
//lblEnddatse.Visible = true;
Boolean status = true;
Util objUtil = new Util();
String Message = "";
DateTime SDate = new DateTime();
DateTime EDate = new DateTime();
string str = "";
DataTable tbl = new DataTable();
DataTable dt = new DataTable();
DataRow dr;
String[] s1;
dt.Clear();
//DirectoryInfo d = new DirectoryInfo();
s1 = Directory.GetFiles(#"C:/TextFiles");
for (int i = 0; i <= s1.Length - 1; i++)
{
if (i == 0)
{
//Add Data Grid Columns with name
dt.Columns.Add("FileName");
dt.Columns.Add("GeneratedTime");
}
//Get each file information
FileInfo f = new FileInfo(s1[i]);
FileSystemInfo f1 = new FileInfo(s1[i]);
dr = dt.NewRow();
//Get File name of each file name
dr["FileName"] = f1.Name;
dr["GeneratedTime"] = f1.CreationTime.Date.ToString("dd/MM/yyyy");
string a = f1.CreationTime.Date.ToString("dd/MM/yyyy");
//Insert collected file details in Datatable
string fromdate = txtFromDate.Text.ToString();
string todate = txtToDate.Text.ToString();
if ((DateTime.ParseExact(a.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture)) >= DateTime.ParseExact(fromdate.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture))
{
if ((DateTime.ParseExact(a.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)) <= DateTime.ParseExact(todate.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
dt.Rows.Add(dr);
}
}
if ((f.Length / 1024) > 5000)
{
lblMessage.Text = "" + f1.Name + " had reach its size limit.";
}
else
{ }
}
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt;
gvFileGenStatus.DataBind();
}
}
How can I refresh the datagridview displayed data every time I click button after I switch the date.
Thanks For the help in advance..
Try:
gvFileGenStatus.Rows.Clear();
dt.Dispose();
or in
DataTable dt_null = new DataTable();
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt_null;
gvFileGenStatus.DataBind();
}
Related
How to convert select new LINQ to DataTable
I need to compare several files using Windows Application form C#.
I have use LINQ and Lambda expression to sum up the duplicates
Please help thanks
I had seen Convert select new to DataTable?. and tried
var firstRecord = records.First();
if (firstRecord == null)
return;
var infos = firstRecord.GetType().GetProperties();
DataTable table = new DataTable();
foreach (var info in infos) {
DataColumn column = new DataColumn(info.Name, info.PropertyType);
table.Columns.Add(column);
}
foreach (var record in records) {
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
row[i] = infos[i].GetValue(record);
table.Rows.Add(row);
}
But it had errors for sequence contains no elements.
These are my full codes.
namespace Comparison2._0
{
public partial class ComparisonForm : Form
{
public class FlatFile
{
public string Location { get; set; }
public string Item_Type { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
}
public ComparisonForm()
{
InitializeComponent();
}
private void UploadTransactionReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
TransactionFileNameTextBox.Text = path;
}
}
private void UploadMovementReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
MovementReportTextBox.Text = path;
}
}
private void UploadFlatfileReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
String[] path = dialog.FileNames;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
for (int i = 0; i < path.Count(); i++)
FlatfileTextBox.Text += path[i] + "#";
}
}
private void UploadAdjustmentReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
AdjustmentReportTextBox.Text = path;
}
}
private void CompareButton_Click(object sender, EventArgs e)
{
OleDbConnection objConn, objConn1, objConn2;
DataTable dt, dt1, dt2, TableA, TableB, TableC;
string sql, sql1, sql2;
OleDbDataAdapter oleDA;
DataSet ds;
string transactionReport = TransactionFileNameTextBox.Text;
string movementReport = MovementReportTextBox.Text;
string adjustmentReport = AdjustmentReportTextBox.Text;
String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
transactionReport + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ movementReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString3 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ adjustmentReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
//TRANSACTION FILE
objConn = new OleDbConnection(sConnectionString1);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql, sConnectionString1);
ds = new DataSet();
oleDA.Fill(ds);
TableA = ds.Tables[0];
objConn.Close();
//dataGridView.DataSource = _DtTable;
//MOVEMENT FILE
objConn1 = new OleDbConnection(sConnectionString2);
objConn1.Open();
dt1 = objConn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql1 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql1, sConnectionString2);
ds = new DataSet();
oleDA.Fill(ds);
TableB = ds.Tables[0];
objConn1.Close();
//dataGridView.DataSource = _DtTable1;
//ADJUSTMENT FILE
objConn2 = new OleDbConnection(sConnectionString3);
objConn2.Open();
dt2 = objConn2.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql2 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql2, sConnectionString3);
ds = new DataSet();
oleDA.Fill(ds);
TableC = ds.Tables[0];
objConn2.Close();
//dataGridView1.DataSource = TableC;
//FLATFILES
//List<string> fileLines = System.IO.File.ReadAllLines(FlatfileTextBox.Text).ToList();
DataTable TableD = ConvertToDataTable(FlatfileTextBox.Text, 4);
//dataGridView1.DataSource = tableD;
DataTable FlatFileTable = new DataTable();
FlatFileTable.Columns.Add(new DataColumn("Location"));
FlatFileTable.Columns.Add(new DataColumn("Item Type"));
FlatFileTable.Columns.Add(new DataColumn("Type"));
FlatFileTable.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
FlatFileTable.Columns.Add(new DataColumn("Amount", typeof(double)));
FlatFileTable.Columns.Add(new DataColumn("Amount Difference"));
foreach (DataRow rowA in TableA.Rows)
{
foreach (DataRow rowD in TableD.Rows)
{
if (Convert.ToDouble(rowD["Amount"]) > 0)
{
if (rowA["Location"].ToString().Substring(0, 5).Trim() == rowD["Location"].ToString() && rowD["Type"].ToString() == "GRN" && rowA["Item Type"].ToString() == rowD["Item Type"].ToString())
{
var newRow = FlatFileTable.NewRow();
newRow["Location"] = rowD["Location"];
newRow["Item Type"] = rowD["Item Type"];
newRow["Type"] = rowD["Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
//sum += Convert.ToDouble(rowD["Amount"]);
newRow["Amount"] = rowD["Amount"];
var newSort = from row in FlatFileTable.AsEnumerable()
group row by new { Location = row.Field<string>("Location"), Item_Type = row.Field<string>("Item Type"), Type = row.Field<string>("Type") } into grp
select new
{
Location = grp.Key.Location,
//Item_Type = grp.Key.Item_Type,
Type = grp.Key.Type,
Amount = grp.Sum(r => r.Field<double>("Amount"))
};
//dataGridView1.DataSource = table;
//newRow["Amount Difference"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowD["Amount"]);
FlatFileTable.Rows.Add(newRow);
//FlatFileTable.Rows.Add(newSort.ToList());
//dataGridView1.DataSource = FlatFileTable;
//DataTable TableZ = newSort.Copt
dataGridView.DataSource = Comparison(TableA, TableB, FlatFileTable);
}
}
}
}
//dataGridView1.DataSource = FlatFileTable;
//dataGridView.DataSource = Comparison(TableA, TableB, newSort.);
//I want to pass into this function so I can compare between them
}
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("Type"));
tbl.Columns.Add(new DataColumn("Amount", typeof(double)));
tbl.Columns.Add(new DataColumn("Location"));
tbl.Columns.Add(new DataColumn("Item Type"));
//foreach(var file in filePath)
string[] MultipleFiles = filePath.Split('#');
for (int i = 0; i < MultipleFiles.Count() - 1; i++)
{
string[] lines = System.IO.File.ReadAllLines(MultipleFiles[i]);
foreach (string line in lines)
{
var cols = line.Split('|');
var count = 0;
DataRow dr = tbl.NewRow();
for (int cIndex = 7; cIndex < 11; cIndex++)
{
dr[count] = cols[cIndex];
count++;
}
tbl.Rows.Add(dr);
}
}
return tbl;
}
public DataTable Comparison(DataTable A, DataTable B, DataTable C)
{
var tableC = new DataTable();
tableC.Columns.Add(new DataColumn("Location"));
tableC.Columns.Add(new DataColumn("Item Type"));
tableC.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
tableC.Columns.Add(new DataColumn("Qty Received Actual Cost"));
tableC.Columns.Add(new DataColumn("Amount from FlatFile"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - Movement)"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - FlatFile)"));
foreach (DataRow rowA in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
foreach (DataRow rowC in C.Rows)
{
if (rowA["Location"].ToString() == rowB["Location"].ToString() && rowA["Item Type"].ToString() == rowB["Item Type"].ToString() &&
rowA["Location"].ToString().Substring(0, 5).Trim() == rowC["Location"].ToString() && rowA["Item Type"].ToString() == rowC["Item Type"].ToString())
{
var newRow = tableC.NewRow();
newRow["Location"] = rowA["Location"];
newRow["Item Type"] = rowA["Item Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
newRow["Qty Received Actual Cost"] = rowB["Qty Received Actual Cost"];
newRow["Amount from FlatFile"] = rowC["Amount"];
newRow["Amount (Transaction - Movement)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowB["Qty Received Actual Cost"]);
newRow["Amount (Transaction - FlatFile)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowC["Amount"]);
tableC.Rows.Add(newRow);
}
//}
}
}
}
return tableC;
}
private void ComparisonForm_Load(object sender, EventArgs e)
{
}
}
}
But it had errors for sequence contains no elements.
You are getting the above error because there is no record in the collection apparently and First fails in that case. You need FirstOrDefault which will return null if there is no items in the collection:
var firstRecord = records.FirstOrDefault();
I want to export a file by calling a stored procedures from aspx and I want to save the data to a .txt file. Each column must have specific column length that need to be set. Below is my code, but when I run the program, the output only display column name... and no data appears. It look like program not read the row statement. Please help me
protected void Page_Load(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
string str = "Server=KABS;Database=HOT;uid=sa;pwd=DDD;Connection Timeout=6000";
if (Request.QueryString["ProcessName"] != null)
{
using (SqlConnection con = new SqlConnection(str))
{
if (Request.QueryString["ProcessName"].ToString().Equals("Ebill"))
{
using (SqlCommand cmd = new SqlCommand("AR_Ebill_claim", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string compcode = null;
DateTime dateFrom = DateTime.Now;
DateTime dateTo = DateTime.Now;
string episType = null;
string debtorCode = null;
if (Request.QueryString["compcode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["compcode"])))
{
compcode = null;
}
else
{
compcode = Convert.ToString(Request.QueryString["compcode"]);
}
}
if (Request.QueryString["dateFrom"] != null)
{
DateTime dtFrom = DateTime.Parse(Request.QueryString["dateFrom"]);
dtFrom.ToString("dd-MMM-yyyy");
if (dtFrom == null)
{
dateFrom = DateTime.Now;
}
else
{
dateFrom = dtFrom;
}
}
if (Request.QueryString["dateTo"] != null)
{
DateTime dtTo = DateTime.Parse(Request.QueryString["dateTo"]);
dtTo.ToString("dd-MMM-yyyy");
if (dtTo == null)
{
dateTo = DateTime.Now;
}
else
{
dateTo = dtTo;
}
}
if (Request.QueryString["episType"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["episType"])))
{
episType = null;
}
else
{
episType = Convert.ToString(Request.QueryString["episType"]);
}
}
if (Request.QueryString["debtorCode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["debtorCode"])))
{
debtorCode = null;
}
else
{
debtorCode = Convert.ToString(Request.QueryString["debtorCode"]);
}
}
cmd.Parameters.Add("#compcode", SqlDbType.VarChar, 100);
cmd.Parameters["#compcode"].Value = compcode;
cmd.Parameters.Add("#dateFrom", SqlDbType.SmallDateTime);
cmd.Parameters["#dateFrom"].Value = dateFrom;
cmd.Parameters.Add("#dateTo", SqlDbType.SmallDateTime);
cmd.Parameters["#dateTo"].Value = dateTo;
cmd.Parameters.Add("#episType", SqlDbType.VarChar, 40);
cmd.Parameters["#episType"].Value = episType;
cmd.Parameters.Add("#debtorCode", SqlDbType.VarChar, 100);
cmd.Parameters["#debtorCode"].Value = debtorCode;
con.Open();
//cmd.ExecuteNonQuery();
//gdBill.EmptyDataText = "No Records Found";
//gdBill.DataSource = cmd.ExecuteReader();
//gdBill.DataBind();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
string txt = string.Empty;
if (dt.Columns.Count > 0)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for Text file.
txt += column.ColumnName + "\t\t";
}
}
//Add new line.
txt += "\r\n";
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
txt += row[column.ColumnName].ToString() + "\t\t";
}
//Add new line.
txt += "\r\n";
}
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=E-Billing.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(txt);
Response.Flush();
Response.End();
Cursor.Current = Cursors.AppStarting;
}
}
//cmd.Dispose();
con.Close();
}
}
}
I tested your code and it works like it should. The problem is that the stored procedure AR_Ebill_claim returns zero rows. But there are no errors so the column names do get exported.
I think the problem lies with the parameters. Check those first and test if the stored procedure gives the results you want in SQL server studio or a similar program.
i already got the solutions as my code below :)
if (Request.QueryString["ProcessName"].ToString().Equals("Ebill"))
{
using (SqlCommand cmd = new SqlCommand("AR_Ebill_claim", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string compcode = null;
DateTime dateFrom = DateTime.Now;
DateTime dateTo = DateTime.Now;
string episType = null;
string debtorCode = null;
if (Request.QueryString["compcode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["compcode"])))
{
compcode = null;
}
else
{
compcode = Convert.ToString(Request.QueryString["compcode"]);
}
}
if (Request.QueryString["dateFrom"] != null)
{
DateTime dtFrom = DateTime.Parse(Request.QueryString["dateFrom"]);
dtFrom.ToString("dd-MMM-yyyy");
if (dtFrom == null)
{
dateFrom = DateTime.Now;
}
else
{
dateFrom = dtFrom;
}
}
if (Request.QueryString["dateTo"] != null)
{
DateTime dtTo = DateTime.Parse(Request.QueryString["dateTo"]);
dtTo.ToString("dd-MMM-yyyy");
if (dtTo == null)
{
dateTo = DateTime.Now;
}
else
{
dateTo = dtTo;
}
}
if (Request.QueryString["episType"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["episType"])))
{
episType = null;
}
else
{
episType = Convert.ToString(Request.QueryString["episType"]);
}
}
if (Request.QueryString["debtorCode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["debtorCode"])))
{
debtorCode = null;
}
else
{
debtorCode = Convert.ToString(Request.QueryString["debtorCode"]);
}
}
cmd.Parameters.Add("#compcode", SqlDbType.VarChar, 100);
cmd.Parameters["#compcode"].Value = compcode;
cmd.Parameters.Add("#dateFrom", SqlDbType.SmallDateTime);
cmd.Parameters["#dateFrom"].Value = dateFrom;
cmd.Parameters.Add("#dateTo", SqlDbType.SmallDateTime);
cmd.Parameters["#dateTo"].Value = dateTo;
cmd.Parameters.Add("#episType", SqlDbType.VarChar, 40);
cmd.Parameters["#episType"].Value = episType;
cmd.Parameters.Add("#debtorCode", SqlDbType.VarChar, 100);
cmd.Parameters["#debtorCode"].Value = debtorCode;
con.Open();
//cmd.ExecuteNonQuery();
//gdBill.EmptyDataText = "No Records Found";
//gdBill.DataSource = cmd.ExecuteReader();
//gdBill.DataBind();
string outputFilePath = Server.MapPath("~/Documents/EClaim.txt");
if (File.Exists("~/Documents/EClaim.txt"))
{
File.Delete("~/Documents/EClaim.txt");
}
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
int[] maxLengths = new int[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
maxLengths[i] = dt.Columns[i].ColumnName.Length;
foreach (DataRow row in dt.Rows)
{
if (!row.IsNull(i))
{
int length = row[i].ToString().Length;
if (length > maxLengths[i])
{
maxLengths[i] = length;
}
}
}
}
using (StreamWriter sw = new StreamWriter(outputFilePath, false))
{
//for (int i = 0; i < dt.Columns.Count; i++)
//{
// sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
//}
sw.WriteLine();
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!row.IsNull(i))
{
sw.Write(row[i].ToString().PadRight(maxLengths[i] + 1));
}
else
{
sw.Write(new string(' ', maxLengths[i] + 1));
}
}
sw.WriteLine();
}
sw.Close();
}
//string filePath = "~/Documents/EBilling.txt";
//Response.ContentType = "application/text";
//Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
//Response.TransmitFile(Server.MapPath(filePath));
////Response.End();
}
I am having a Gridview with 1 checkbox column and 3 other columns. To 1 colums I am adding values from a TextBox on ButtonClick.
I want that duplicate values should not displayed in the gridview for which I have added code in Rowdatabound.
The code works perfectly when paging is disabled but when paging is enabled code works only if a duplicate value is added to the same page but if the value being added is to the next page the value is accepted.
protected void GVRequest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//switch for first row
if (e.Row.RowIndex == 1)
{
GridViewRow Gprev = GVRequest.Rows[e.Row.RowIndex - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
e.Row.Cells[1].Text = "";
e.Row.Visible = false;
}
}
//now continue with the rest of the rows
if (e.Row.RowIndex > 1)
{
//set reference to the row index and the current value
int intC = e.Row.RowIndex;
string lookfor = e.Row.Cells[1].Text;
//now loop back through checking previous entries for matches
do
{
GridViewRow Gprev = GVRequest.Rows[intC - 1];
if (Gprev.Cells[1].Text.Equals(e.Row.Cells[1].Text))
{
//e.Row.Cells[0].Text = "";
//e.Row.Cells[1].Text = "";
//e.Row.Cells[2].Text = "";
//e.Row.Cells[3].Text = "";
e.Row.Visible = false;
//Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID already added for processing');", true);
}
intC = intC - 1;
} while (intC > 0);
}
}
}
protected void GVRequest_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
//DataRow drCurrentRow = null;
GVRequest.PageIndex = e.NewPageIndex;
GVRequest.DataSource = dtCurrentTable;
//SetPreviousData();
//GVRequest.DataBind();
DataBind();
}
//Add new Row
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
try
{
string RequestID = Request.QueryString["RequestID"];
SqlConnection conn = new SqlConnection(GetConnectionString());
StringBuilder sb = new StringBuilder(string.Empty);
const string SQLFileRetrievalReq = "SELECT DeptFileID, FileStatus, FileID, RequestID FROM FileInwardMaster WHERE (FileID = #FileID) AND (RequestID = #RequestID)";
SqlCommand cmdFileRetrievalReq = new SqlCommand(SQLFileRetrievalReq, conn);
cmdFileRetrievalReq.Parameters.Add("#RequestID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#RequestID"].Value = RequestID;
cmdFileRetrievalReq.Parameters.Add("#FileID", SqlDbType.VarChar);
cmdFileRetrievalReq.Parameters["#FileID"].Value = TextBoxFileIds.Text.ToString();
conn.Open();
SqlDataReader reader = cmdFileRetrievalReq.ExecuteReader();
reader.Read();
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["SlNo"] = dtCurrentTable.Rows.Count + 1;
drCurrentRow["FileID"] = TextBoxFileIds.Text.ToUpper();
drCurrentRow["RequestID"] = RequestID;
drCurrentRow["DeptFileID"] = reader["DeptFileID"].ToString();
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
GVRequest.DataSource = dtCurrentTable;
GVRequest.DataBind();
}
catch
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('ID Entered/Scanned not valid for Request. Please Enter/Scan a valid ID to proceed');", true);
SetPreviousData();
//SetInitialRow();
//GVRequest.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
//Get Previous Data
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["FileID"].ToString();// = txtRcptHdNo.Text;
dt.Rows[i]["RequestID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
dt.Rows[i]["DeptFileID"].ToString();// = ddlRcptDtlsItem.SelectedItem.Text;
rowIndex++;
}
}
}
}
private void SetInitialRow()
{
string RequestID = Request.QueryString["RequestID"];
DataTable dt = new DataTable();
//DataRow dr = null;
dt.Columns.Add(new DataColumn("RequestID", typeof(string)));
dt.Columns.Add(new DataColumn("FileID", typeof(string)));
dt.Columns.Add(new DataColumn("DeptFileID", typeof(string)));
// dr = dt.NewRow();
// dr["RequestID"] = string.Empty;
//dr["FileID"] = string.Empty;
//dr["DeptFileID"] = string.Empty;
//dt.Rows.Add(dr);
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
GVRequest.DataSource = dt;
GVRequest.DataBind();
}
protected void BtnAddFileID_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
//GenerateUniqueData(0);
TextBoxFileIds.Text = "";
}
I am trying to bind a repeater with some fixed values when datatable is empty.
My code is
if (dt.Rows.Count == 0)
{
DataTable temp = new DataTable();
temp.Columns.Add("banner_id");
DataRow drs = temp.NewRow();
drs["banner_id"] = 1;
temp.Rows.Add(drs);
temp.AcceptChanges();
rpt_slider.DataSource = temp;
rpt_slider.DataBind();
}
else
{
rpt_slider.DataSource = dt;
rpt_slider.DataBind();
}
I want to show at lest one record when datatable is empty
protected void getdata()
{
property.banner_id = 0;
property.banner_type = "Primary";
DataSet ds = bal.getdata_view(property.banner_id, property.banner_type);
DataTable dt = ds.Tables[0];
ViewState["getdata_primary"] = dt;
if (dt.Rows.Count > 0)
{
rptMain.DataSource = bal.getdata_view(property.banner_id, property.banner_type);
rptMain.DataBind();
lblmsg.Text = "";
lblmsg.Visible = false;
Button5.Visible = true;
}
}
you need to make this changes in code of getdata() please change it...
I'm working with entity framework and right now I'm saving two assignments and want to show them to my gridview.
Here I'm saving them to my database table and show them in the gridview:
The code here:
protected void ButtonAddAssignmentClick(object sender, EventArgs e)
{
Session.Remove("DataTable");
//Add to DB and show in gridview
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmplAssignment = (
from p
in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
_emp = theEmplAssignment;
if (_emp != null)
{
//Create assignment
var myAssignment = new EMPLOYEES_ASSIGNMENT
{
assignment_id = new Random().Next(),
employee_id = _emp.employee_id,
reference_name = TextBoxReference.Text,
company_name = TextBoxCompanyName.Text,
sector = TextBoxSector.Text,
area = TextBoxArea.Text,
from_date = TextBoxFromDate.Text,
to_date = TextBoxToDate.Text,
description = TextBoxDesc.Text,
};
//Create assignment tools
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
var myTool = new ASSIGNMENT_TOOLS
{
assignment_tools_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
tool_name = ListBoxAssignmentTools.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TOOLS.Add(myTool);
}
//Create assignment technology
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
var myTech = new ASSIGNMENT_TECHNOLOGY
{
assignment_technology_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
technology_name = ListBoxAssignmentTechnology.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TECHNOLOGY.Add(myTech);
}
//Add assignment to db
_emp.EMPLOYEES_ASSIGNMENT.Add(myAssignment);
db.SaveChanges();
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = TextBoxCompanyName.Text;
dr["Sector"] = TextBoxSector.Text;
dr["Area"] = TextBoxArea.Text;
dr["From"] = TextBoxFromDate.Text;
dr["To"] = TextBoxToDate.Text;
dr["Description"] = TextBoxDesc.Text;
dr["Reference"] = TextBoxReference.Text;
string sToolsValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
sToolsValue += ListBoxAssignmentTools.Items[i] + " ";
}
dr["Tools"] = sToolsValue;
string sTechValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
sTechValue += ListBoxAssignmentTechnology.Items[i] + " ";
}
dr["Technology"] = sTechValue;
dt.Rows.Add(dr);
Session["DataTable"] = dt;
//Add to gridview
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
TextBoxCompanyName.Text = string.Empty;
TextBoxArea.Text = string.Empty;
TextBoxSector.Text = string.Empty;
TextBoxFromDate.Text = string.Empty;
TextBoxToDate.Text = string.Empty;
TextBoxDesc.Text = string.Empty;
TextBoxReference.Text = string.Empty;
ListBoxAssignmentTools.Items.Clear();
ListBoxAssignmentTechnology.Items.Clear();
}
}
}
And I'm using a method on page load that retrieves all assignments on the current logged in user and showing it on the gridview.
But the gridview is populating duplicates! I suspect that I must clear my session on page load but I don't really know how to do it.
The method code:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session.Remove("DataTable");
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
foreach (var vAssignment in assignmentList)
{
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
LabelUsername.Text = strUserName;
if (!IsPostBack)
{
_emp = GetEmployee(strUserName);
GetEmployeeAssignment(_emp);
}
}
Just do
Session["DataTable"] = null;
or
Session.Remove("DataTable")
Update your code like:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session["DataTable"]=null;
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
var dt = new DataTable();
foreach (var vAssignment in assignmentList)
{
//Populate gridview
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
}
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Best Regards