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();
}
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 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();
}
I have one dynamically generated html table in my web application.One of its column list out asp checkboxes controls. I want to select multiple rows(by checkboxex)to publish,unpublish or delete my articles. It successfully publishes or unpublishes for the first postback of asp button. But when i click for the second time it sends false for all the checkboxex even some of them are selected.So I expect it must work for the second postback if it works for the first time because it had successfully passed all the page life cycle for the first time then why not for the second time..I am really confused.Please help me
Here is my code:
// For dynamically generated controls i used oninit state
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!this.DesignMode)
{
ds = GetArticles();
FillArticleTable();
}
}
// Code for page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string eventdata = Request.QueryString["event"];
int id = Convert.ToInt32(Request.QueryString["id"]);
if (eventdata != "edt")
{
Actions(id, eventdata);
}
else
{
Response.Redirect("Articles.aspx?id=" + id + "");
}
}
else
{
ds = GetArticles();
Cache["Articles"] = ds;
}
}
}
// Code for Button Click event
protected void btnApplyAction_Click(object sender, EventArgs e)
{
if (this.ddlActions.SelectedValue != "none")
{
IterateOverHtmlTable(this.ddlActions.SelectedValue);
this.myTable.Rows.Clear();
ds = GetArticles();
FillArticleTable();
}
}
// Code For retrieving Articles from database
private DataSet GetArticles()
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(#"Data Source = xenz-pc\sqlexpress; Initial Catalog =MedicalSystem2; User Id =sa; Password =sa;");
SqlCommand com = new SqlCommand("Select A.ID,A.ArticleTitle,A.Author,C.Category, A.Published,A.CreatedON,A.ModifiedON from Articles as A Inner Join Category As C On A.Category_ID = C.ID ", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = com;
adp.Fill(ds);
con.Close();
return ds;
}
//Code For Dynamically generating html table
private void FillArticleTable()
{
int rows = 0;
string imgsource;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
HtmlTableRow row = new HtmlTableRow();
rows = rows + 1;
Object[] fields = ds.Tables[0].Rows[i].ItemArray;
if (Convert.ToBoolean(fields[4]) == false)
{
imgsource = "minus-circle.gif";
}
else
{
imgsource = "tick-circle.gif";
}
for (int j = 0; j < fields.Length; j++)
{
HtmlTableCell cell = new HtmlTableCell();
if (j == 0)
{
HtmlTableCell srno = new HtmlTableCell();
srno.InnerText = rows.ToString();
cell.InnerText = fields[j].ToString();
row.Cells.Add(srno);
row.Cells.Add(cell);
}
else if (j == 1)
{
cell.InnerText = fields[j].ToString();
row.Cells.Add(cell);
}
else if (j == 2)
{
cell.InnerText = fields[j].ToString();
row.Cells.Add(cell);
}
else if (j == 3)
{
cell.InnerText = fields[j].ToString();
row.Cells.Add(cell);
}
else if (j == 4)
{
cell.InnerHtml = #"<img src=" + imgsource + " 'width=16' 'height=16' alt='published/unpublished'";
row.Cells.Add(cell);
}
else if (j == 5)
{
cell.InnerText = String.Format("{0:d}", fields[j]);
row.Cells.Add(cell);
}
else if (j == 6)
{
cell.InnerText = String.Format("{0:d}", fields[j]);
HtmlTableCell checkboxes = new HtmlTableCell();
checkboxes.Align = "Right";
HtmlTableCell actions = new HtmlTableCell();
CheckBox chkactionbox = new CheckBox();
chkactionbox.EnableViewState = true;
checkboxes.Controls.Add(chkactionbox);
actions.InnerHtml = #"<a href='ManageArticles.aspx?id=" + fields[0].ToString() + "&event=pu'><img src='tick-circle.gif' 'width=16' 'height=16' alt='published' /></a><a href='ManageArticles.aspx?id=" + fields[0].ToString() + "&event=upu'><img src='minus-circle.gif' width='16' height='16' alt='not published' /></a><a href='ManageArticles.aspx?id=" + fields[0].ToString() + "&event=edt'><img src='pencil.gif' width='16' height='16' alt='edit' /></a><a href='ManageArticles.aspx?id=" + fields[0].ToString() + "&event=del'><img src='bin.gif' width='16' height='16' alt='delete' /></a>";
row.Cells.Add(cell);
row.Cells.Add(checkboxes);
row.Cells.Add(actions);
}
}
this.myTable.Rows.Add(row);
}
}
//Code For Finding out checkboxes which are selected by user
private void IterateOverHtmlTable(string eventdata)
{
HtmlTable table = (HtmlTable)Page.FindControl("myTable");
int count = 0;
foreach (HtmlTableRow row in table.Rows)
{
count = count + 1;
if (count > 1)
{
foreach (CheckBox item in row.Cells[8].Controls)
{
if (item.Checked)
{
Actions(Convert.ToInt32(row.Cells[1].InnerText), eventdata);
}
}
}
}
}
// Code For Publish,Unpublish and Delete Actions
private void Actions(int id, string eventdata)
{
if (Connection != null)
{
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
}
else
{
Connection = new SqlConnection(#"Data Source = xenz-pc\sqlexpress; Initial Catalog =MedicalSystem2; User Id =sa; Password =sa;");
if (Connection.State != ConnectionState.Open)
{
Connection.Open();
}
}
SqlCommand com = new SqlCommand();
int rows;
if (eventdata == "pu")
{
com.CommandText = "Update Articles Set Published = 'true' Where ID = " + id;
com.CommandType = CommandType.Text;
com.Connection = Connection;
rows = com.ExecuteNonQuery();
Connection.Close();
if (rows > 0)
{
this.Publish.InnerText = "Published";
}
}
else if (eventdata == "upu")
{
com.CommandText = "Update Articles Set Published = 'false' Where ID = " + id;
com.CommandType = CommandType.Text;
com.Connection = Connection;
rows = com.ExecuteNonQuery();
Connection.Close();
if (rows > 0)
{
this.Unpublish.InnerText = "Unpublished";
}
}
else
{
com.CommandText = "Delete From Articles Where ID =" + id;
com.CommandType = CommandType.Text;
com.Connection = Connection;
rows = com.ExecuteNonQuery();
Connection.Close();
if (rows > 0)
{
this.Publish.InnerText = "Deleted";
}
}
}
There are two things I noticed that might be of use:
You can use data bound control or HTML controls to achieve what you've hardcoded already.
Every time button is clicked checkboxes are recreated and that means the check state will reset.
Im trying to fill a DataGridView with the results from a MySql Query however they are not all going in. Here is my code:
try
{
conn.Open();
player_search = new MySqlCommand("SELECT * FROM admin;", conn);
reader = player_search.ExecuteReader();
int counter = 0;
while (reader.Read())
{
player_list[0, counter].Value = reader.GetString(0);
player_list[1, counter].Value = reader.GetString(1);
player_list[2, counter].Value = reader.GetString(6);
player_list[3, counter].Value = reader.GetString(7);
player_list[4, counter].Value = reader.GetString(8);
player_list[5, counter].Value = reader.GetString(9);
player_list[6, counter].Value = "Remove";
counter = counter+1;
}
}
However it doesnt all go in. It only inserts the first row of the query? Why is it doing this? Im getting no errors?
Solved it! I had to do a long winded approach but it works!
MySqlCommand mysqlcmd = new MySqlCommand("SELECT * FROM admin;", conn);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
player_list.DataSource = dt;
int rowIndex = 0;
foreach (DataRow row in dt.Rows)
{
int i = 0;
foreach (var item in row.ItemArray)
{
if (i == 0) {
player_list[0, rowIndex].Value = item.ToString();
}
if (i == 1) {
player_list[1, rowIndex].Value = item.ToString();
}
if (i == 4)
{
player_list[2, rowIndex].Value = item.ToString();
}
if (i == 7)
{
player_list[3, rowIndex].Value = item.ToString();
}
if (i == 8)
{
player_list[4, rowIndex].Value = item.ToString();
}
if (i == 9)
{
player_list[5, rowIndex].Value = item.ToString();
}
player_list[6, rowIndex].Value = "Remove";
++i;
}
++rowIndex;
i = 0;
}
I would suggest you to try to get it using DataSet:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
UPDATE: player_list.DataSource(GetDBDataTable(...));
player_list.DataBind();
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