I coded this for my code what im trying to do is for each of the accounts made in a database it adds it to the datagridviewi tried this code but all the comums are empty?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
public frmMain()
{
this.InitializeComponent();
this.SetupBackstageContent();
ribbonControl1.SelectedRibbonTabItem = ribbonTabItem1;
ribbonTabItem2.Text = "&USER CONTROL";
ribbonTabItem4.Text = "&ADD ONS";
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
}
Your way is wrong,if you want fill dataGrid with all user records just consider this code:
using (SqlConnection conn = new SqlConnection("your connection string"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM users", conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds;
}
Conn();
int i = 0;
cmd = new SqlCommand("select * from tbl_Emp", con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
if (Dgv_Emp.Rows.Count > 0)
{ Dgv_Emp.Rows.Clear(); }
Dgv_Emp.Rows.Add(dt.Rows.Count);
foreach (DataRow rw in dt.Rows)
{
Dgv_Emp.Rows[i].Cells[0].Value = rw["Emp_id"].ToString();
Dgv_Emp.Rows[i].Cells[1].Value = rw["Emp_name"].ToString();
Dgv_Emp.Rows[i].Cells[2].Value = rw["Emp_desg"].ToString();
Dgv_Emp.Rows[i].Cells[3].Value = rw["Emp_dept"].ToString();
Dgv_Emp.Rows[i].Cells[4].Value = rw["Emp_gender"].ToString();
Dgv_Emp.Rows[i].Cells[5].Value = rw["Emp_contact"].ToString();
i = i + 1;
}
}
Please use following code:
public DataTable GetResultsTable()
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataTable _userTable = client.ExecuteQueryTable("SELECT * FROM users");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
foreach (DataRow _row in _userTable.Rows)
{
DataRow dr = table.NewRow();
dr["Username"] = "" + _row["username"] + "";
dr["Motto"] = "" + _row["motto"] + "";
dr["Email"] = "" + _row["mail"] + "";
dr["Homeroom"] = "" + _row["home_room"] + "";
dr["Health"] = "" + _row["health"] + "";
dr["Energy"] = "" + _row["energy"] + "";
dr["Age"] = "" + _row["age"] + "";
table.Rows.Add(dr);
}
return table;
}
}
public frmMain()
{
this.InitializeComponent();
this.SetupBackstageContent();
ribbonControl1.SelectedRibbonTabItem = ribbonTabItem1;
ribbonTabItem2.Text = "&USER CONTROL";
ribbonTabItem4.Text = "&ADD ONS";
SqlDatabaseManager.Initialize();
dataGridView1.DataSource = GetResultsTable();
}
Since u r passing DataRow as DataSource for DataGridView view hence only last row would be in datagridview. Here I change ur code and bind DataTable rather than DataRow with DataSource of DataGridView.
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 making a webmethod in asmx, in which i am getting data from different tables... and populate row in dataset.. but how can i fill my dataset as i am getting data from different table???
kindly help me :(
[WebMethod]
public DataSet getblancesheet(string baranchcode, string fromdate, string todate)
{
// List<datalist4> data = new List<datalist4>();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt4 = new DataTable();
DataTable finaldata = new DataTable();
Webservice.databaseops dbo = new Webservice.databaseops();
DataSet ds = new DataSet("Ledger");
SqlDataAdapter adp = new SqlDataAdapter();
//adp.Fill(ds);
bool sheet1, sheet2, sheet3;
sheet1 = sheet2 = sheet3 = true;
decimal sheet1bal, sheet2bal, sheet3bal;
sheet1bal = sheet2bal = sheet3bal = 0;
dt1 = dbo.getdata("SELECT Bcode,Bdesc FROM Gl_bSheet1 where Compcode='" + baranchcode + "'");
if (dt1.Rows.Count > 0)
{
foreach (DataRow dr1 in dt1.Rows)
{
// sheet1
dt2 = dbo.getdata("SELECT Bncode,Bndesc FROM Gl_bSheet2 where Compcode='" + baranchcode + "' and Bcode='" + dr1[0] + "'");
if (dt2.Rows.Count > 0)
{
foreach (DataRow dr2 in dt2.Rows)
{
//sheet2
dt3 = dbo.getdata("SELECT Bnicode,Bnidesc FROM Gl_bSheet3 where Compcode='" + baranchcode + "' and Bcode='" + dr1[0] + "' and Bncode='" + dr2[0] + "'");
if (dt3.Rows.Count > 0)
{
foreach (DataRow dr3 in dt3.Rows)
{
//sheet3
dt4 = dbo.getdata("SELECT gpls.Accountno,gd.Acct_Desc FROM Gl_bSheetdetail gpls,GL_Detail gd where gpls.Compcode='" + baranchcode + "' and gpls.Bcode='" + dr1[0] + "' and gpls.Bncode='" + dr2[0] + "' and gpls.Bnicode='" + dr3[0] + "' and gpls.Accountno=gd.AccountNo");
if (dt4.Rows.Count > 0)
{
foreach (DataRow dr4 in dt4.Rows)
{
//detialsheet
finaldata = dbo.getdata("SELECT SUM(Dr_Amount)-SUM(Cr_Amount) from gl_transaction where Accountno='" + dr4[0] + "' and Value_Date between '" + fromdate + "' and '" + todate + "'");
if (finaldata.Rows[0].ItemArray[0].ToString().Length > 0)
{
if (sheet1)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = dr1[1].ToString();
dd[1] = "sheet1";
dd[2] = "";
dd[3] = "";
ds.Tables[0].Rows.Add(dd);
sheet1 = false;
// data.Add(new datalist4(dr1[1].ToString(), "sheet1", "", ""));
// sheet1 = false;
}
}
if (sheet2)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = dr2[1].ToString();
dd[1] = "sheet2";
dd[2] = "";
dd[3] = "";
ds.Tables[0].Rows.Add(dd);
sheet2 = false;
//data.Add(new datalist4(dr2[1].ToString(), "sheet2", "", ""));
//sheet2 = false;
}
}
if (sheet3)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = dr3[1].ToString();
dd[1] = "sheet3";
dd[2] = "";
dd[3] = "";
ds.Tables[0].Rows.Add(dd);
//data.Add(new datalist4(dr3[1].ToString(), "sheet3", "", ""));
//sheet3 = false;
sheet3 = false;
}
}
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = "-";
dd[1] = dr4[0].ToString().Trim();
dd[2] = dr4[1].ToString().Trim();
dd[3] = dbo.valueparser(decimal.Parse(finaldata.Rows[0].ItemArray[0].ToString()), false);
ds.Tables[0].Rows.Add(dd);
}
//data.Add(new datalist4("-", dr4[0].ToString().Trim(), dr4[1].ToString().Trim(), dbo.valueparser(decimal.Parse(finaldata.Rows[0].ItemArray[0].ToString()), false)));
sheet1bal = sheet1bal + decimal.Parse(finaldata.Rows[0].ItemArray[0].ToString());
sheet2bal = sheet2bal + decimal.Parse(finaldata.Rows[0].ItemArray[0].ToString());
sheet3bal = sheet2bal + decimal.Parse(finaldata.Rows[0].ItemArray[0].ToString());
}
}
}
if (!sheet3)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = "sheet3end";
dd[1] = "SubTotal";
dd[2] = dr3[1].ToString();
dd[3] = dbo.valueparser(sheet3bal, false);
ds.Tables[0].Rows.Add(dd);
//data.Add(new datalist4("sheet3end", "Subtotal:", dr3[1].ToString(), dbo.valueparser(sheet3bal, false)));
sheet3 = true;
sheet3bal = 0;
}
}
}
}
if (!sheet2)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = "sheet2end";
dd[1] = "SubTotal:";
dd[2] = dr2[1].ToString();
dd[3] = dbo.valueparser(sheet2bal, false);
ds.Tables[0].Rows.Add(dd);
// data.Add(new datalist4("sheet2end", "Subtotal:", dr2[1].ToString(), dbo.valueparser(sheet2bal, false)));
sheet2 = true;
sheet2bal = 0;
}
}
}
}
if (!sheet1)
foreach (DataRow dr in ds.Tables[0].Rows)
{
DataRow dd = ds.Tables[0].NewRow();
dd[0] = "sheet1end";
dd[1] = "SubTotal:";
dd[2] = dr1[1].ToString();
dd[3] = dbo.valueparser(sheet2bal, false);
ds.Tables[0].Rows.Add(dd);
//data.Add(new datalist4("sheet1end", "Subtotal:", dr1[1].ToString(), dbo.valueparser(sheet1bal, false)));
sheet1 = true;
sheet1bal = 0;
}
}
}
return ds;
}
//do
I've done a bit of refactoring of your code and I think I've got a reasonable solution for you. Try something like this to get your data:
var data =
from DataRow dr1 in dbo.getdata("SELECT Bcode,Bdesc FROM Gl_bSheet1 where Compcode='" + baranchcode + "'").Rows
let Bcode = (string)dr1[0]
select new
{
Bcode,
Bdesc = (string)dr1[1],
sheet2s =
from DataRow dr2 in dbo.getdata("SELECT Bncode,Bndesc FROM Gl_bSheet2 where Compcode='" + baranchcode + "' and Bcode='" + Bcode + "'").Rows
let Bncode = (string)dr2[0]
select new
{
Bncode,
Bndesc = (string)dr2[1],
sheet3s =
from DataRow dr3 in dbo.getdata("SELECT Bnicode,Bnidesc FROM Gl_bSheet3 where Compcode='" + baranchcode + "' and Bcode='" + Bcode + "' and Bncode='" + Bncode + "'").Rows
let Bnicode = (string)dr3[0]
select new
{
Bnicode,
Bnidesc = (string)dr3[1],
dataSheets =
from DataRow dr4 in dbo.getdata("SELECT gpls.Accountno,gd.Acct_Desc FROM Gl_bSheetdetail gpls,GL_Detail gd where gpls.Compcode='" + baranchcode + "' and gpls.Bcode='" + Bcode + "' and gpls.Bncode='" + Bncode + "' and gpls.Bnicode='" + Bnicode + "' and gpls.Accountno=gd.AccountNo").Rows
let Accountno = (string)dr4[0]
let finaldata = (string)(dbo.getdata("SELECT SUM(Dr_Amount)-SUM(Cr_Amount) from gl_transaction where Accountno='" + Accountno + "' and Value_Date between '" + fromdate + "' and '" + todate + "'").Rows[0].ItemArray[0])
where !String.IsNullOrEmpty(finaldata)
select new
{
Accountno,
Acct_Desc = (string)dr4[1],
value = decimal.Parse(finaldata)
}
}
}
};
And then generate your rows with this code:
foreach (var s1 in data)
{
var dd = ds.Tables[0].NewRow();
dd[0] = s1.Bdesc;
dd[1] = "sheet1";
dd[2] = "";
dd[3] = "";
ds.Tables[0].Rows.Add(dd);
foreach (var s2 in s1.sheet2s)
{
//Add Sheet2 Opening Row Here
foreach (var s3 in s2.sheet3s)
{
//Add Sheet3 Opening Row Here
//Add Data Row Here
var s3balance = s3.dataSheets
.Select(z => z.value)
.Sum();
//Add Sheet3 Closing Row Here
}
var s2balance = s2.sheet3s
.SelectMany(y => y.dataSheets)
.Select(z => z.value)
.Sum();
//Add Sheet2 Closing Row Here
}
var s1balance = s1.sheet2s
.SelectMany(x => x.sheet3s)
.SelectMany(y => y.dataSheets)
.Select(z => z.value)
.Sum();
//Add Sheet1 Closing Row Here
}
It's usually a good idea to keep the query away from the code that writes the data. I think this does it quite well.
Im trying to add all my users accounts to a gridview but when using the foreach code it is only adding the last value of the datagridview. Is there a way to do all of them?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
The DataSource property of a DataGridView object shouldn't be one row, but many.
So you can change your code to create a list first and apply this as the DataSource, OR you use the following method:
dataGridView1.Rows.Add(GetResultsTable(row2["username"].ToString());
In the foreach loop.
Hope it helps you out :).
you can use one method to load the data
public DataTable fillDataTable()
{
// select all the columns with expected column name, here I only added 3 columns
string query = "SELECT username as Username, motto as Motto, mail as Email FROM users;
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
set the grid DataSource like below
dataGridView1.DataSource =fillDataTable();
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 am using window.open to open 2 different pages in pop-up windows,but for some reason both the triggers opens the same page in the pop-up window,heres how I am trying to do this:
first:
Response.Write("<script type='text/javascript'>window.open('TransEditEntry.aspx','mywindow','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
second:
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
this opens 'TransEditEntry.aspx' page instead of 'TransNewEntry.aspx'`
here the rest of the code:
The entire function which is called on add button click:
protected void addNew(object sender, EventArgs e)
{
//HiddenField sr = (HiddenField)GridView1.SelectedRow.Cells[6].FindControl("srno");
//Session["TransSrNo"] = sr.Value;
Response.Write(#"<script type='text/javascript'>window.open('TransNewEntry.aspx','','width=850px,height=300px,left=0,top=10,screenX=100,screenY=10')</script>");
//Session["transAdd"] = "1";
}
The add button which calls the function:
<asp:Button ID="AddBtn" runat="server" OnClick="addNew" Text="Add"/>
The page TransNewEntry.aspx.cs
public partial class TransEditEntry : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(GetConnectionString.Get());
string subCode;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder build;
DataRow dr;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
Response.Write((Session["TransSrNo"]).ToString());
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
con.Open();
SqlCommand cmd3 = new SqlCommand("select sub_code from tran_dtls where sr_no='" + SRno + "'", con);
subCode = (string)cmd3.ExecuteScalar();
con.Close();
if (!IsPostBack)
{
sda = new SqlDataAdapter("select * from tran_dtls where sr_no=" + SRno + "", con);
build = new SqlCommandBuilder(sda);
dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
srNoTxt.Text = "";
amttxt.Text = "";
partTxt.Text = "";
checkNoTxt.Text = "";
checkDtTxt.Text = "";
refNoTxt.Text = "";
refDtTxt.Text = "";
jobNoTxt.Text = "";
}
}
}
protected void GlChange(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd4 = new SqlCommand("select ac_type from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string acType = (string)cmd4.ExecuteScalar();
SqlCommand cmd5 = new SqlCommand("select gl_code from ac_mstr where AC_desc='" + GlDrp.SelectedValue + "'", con);
string gl_code = (string)cmd5.ExecuteScalar();
if (acType == "S")
{
SqlDataSource3.SelectCommand = ("select ac_desc from ac_mstr where gl_code='" + gl_code + "'");
subDrp.DataBind();
subDrp.Enabled = true;
//Response.Write("<script type='javacript/text'>alert('1')</script>");
}
else
{
subDrp.Enabled = false;
//Response.Write("<script type='javacript/text'>alert('2')</script>");
}
con.Close();
}
protected void saveRow(object sender, EventArgs e)
{
int SRno = Convert.ToInt32((Session["TransSrNo"]).ToString());
sda = new SqlDataAdapter("select * from tran_dtls where tc='" + Session["TC"] + "' and doc_no='" + Session["docNo"] + "' ", con);
build = new SqlCommandBuilder(sda);
//dt = new DataTable();
// DataSet ds = new DataSet();
sda.Fill(ds);
dt = (DataTable)ViewState["myViewState"];
if (Session["gridRow"] == null)
{
dt = ds.Tables[0];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
else
{
dt = (DataTable)Session["gridRow"];
dr = dt.NewRow();
dr["GL_code"] = GlDrp.SelectedValue;
dr["sub_code"] = subDrp.SelectedValue;
dr["particulars"] = partTxt.Text;
dr["chq_no"] = checkNoTxt.Text;
dr["chq_dt"] = checkDtTxt.Text;
dr["ref_no"] = refNoTxt.Text;
dr["ref_dt"] = refDtTxt.Text;
dr["dbcr"] = dbcrDrp.SelectedValue.ToString().Substring(0, 1);
dr["amt"] = amttxt.Text;
dr["job_no"] = jobNoTxt.Text;
dr["EMP"] = empDrop.SelectedValue;
dt.Rows.Add(dr);
dt.AcceptChanges();
ViewState["myViewState"] = dt;
//Session["gridRow"] = dt;
Session["gridRow"] = dt;
Session["saveToggle"] = "1";
//Response.Write("<script type='text/javascript'>window.opener.location.reload(true);</script>");
closeFunction();
Response.Write("<script type='text/javascript'>this.close()</script>");
}
}
private void closeFunction()
{
StringBuilder sb = new StringBuilder();
sb.Append("window.opener.RefreshPage();");
sb.Append("window.close();");
ClientScript.RegisterClientScriptBlock(this.GetType(), "CloseWindowScript", sb.ToString(), true);
}
}
Check your condition where you are doing : Response.Write. Both the conditions must be pointing out for first>