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.
Related
XML File:
<?xml version="1.0" encoding="utf-8"?>
<Data xmlns:xsd="http://www.hbjhgjgjg.com/1889/XMLSchema"
xmlns:xsi="http://www.hbjhgjgjg.com/1889/XMLSchema-instance"
xmlns="http://www.ytutu.com/data/schema/XXXa/1829">
<Header>
<ContentDate>2018-03-16T00:00:37.511-06:00</ContentDate>
<Originator>12344</Originator>
<FileContent>abc</FileContent>
<RecordCount>890</RecordCount>
</Header>
<Records>
<XXXRecord>
<XXX>8888834</XXX>
<Entity>
<Name xml:lang="es">NAME CV</Name>
<OtherEntityNames>
<OtherEntityName xml:lang="es" type="OTHER NAME"></OtherEntityName>
<OtherEntityName xml:lang="es" type="OTHER NAME1">ABGT</OtherEntityName>
</OtherEntityNames>
<Address xml:lang="es">
<FirstAddressLine>898 RTT</FirstAddressLine>
<AddressNumber>32</AddressNumber>
<AdditionalAddressLine>eddff</AdditionalAddressLine>
<AdditionalAddressLine>hghg</AdditionalAddressLine>
<City>CITY</City>
<Region>REGION</Region>
<Country>COUNTRY</Country>
<PostalCode>79799</PostalCode>
</Address>
<FirstAddress xml:lang="es">
<FirstAddressLine>rafgaf</FirstAddressLine>
<AddressNumber>32</AddressNumber>
<AdditionalAddressLine>gggg</AdditionalAddressLine>
<AdditionalAddressLine>jjgjgg</AdditionalAddressLine>
<City>CITY</City>
<Region>REGION</Region>
<Country>COUNTRY</Country>
<PostalCode>34433</PostalCode>
</FirstAddress>
<OtherAddresses>
<OtherAddress xml:lang="es" type="ADDRESS">
<FirstAddressLine>ggh</FirstAddressLine>
<AddressNumber>32</AddressNumber>
<AdditionalAddressLine>guhgu</AdditionalAddressLine>
<AdditionalAddressLine>tryryry</AdditionalAddressLine>
<City>CITY</City>
<Region>REGION</Region>
<Country>COUNTRY</Country>
<PostalCode>09090</PostalCode>
</OtherAddress>
</OtherAddresses>
<Confirmation>
<ID>77878</ID>
<EntityID>dsfdd</EntityID>
</Confirmation>
</Entity>
</Record>
and many similar records below...
I used the below code to convert XML to EXCEL file. I am using .net windows application. But the output excel file shows only the header data with 4 row counts. It is not reading all the values from the dataset. The dataset has all the values.
Is there any other method I can implement this?
private void Convert_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
if (checkBox1.Checked && txtCustomeFileName.Text != "" && txtXmlFilePath.Text != "") // using Custome Xml File Name
{
if (File.Exists(txtXmlFilePath.Text))
{
string CustXmlFilePath = Path.Combine(new FileInfo(txtXmlFilePath.Text).DirectoryName, txtCustomeFileName.Text); // Creating Path for Xml Files
System.Data.DataTable dt = CreateDataTableFromXml(txtXmlFilePath.Text);
ExportDataTableToExcel(dt, CustXmlFilePath);
MessageBox.Show("Conversion Completed!!");
}
}
else if (!checkBox1.Checked || txtXmlFilePath.Text != "") // Using Default Xml File Name
{
if (File.Exists(txtXmlFilePath.Text))
{
FileInfo fi = new FileInfo(txtXmlFilePath.Text);
string XlFile = fi.DirectoryName + "\\" + fi.Name.Replace(fi.Extension, ".xlsx");
System.Data.DataTable dt = CreateDataTableFromXml(txtXmlFilePath.Text);
ExportDataTableToExcel(dt, XlFile);
MessageBox.Show("Conversion Completed!!");
}
}
else
{
MessageBox.Show("Please Fill Required Feilds!!");
}
}
// Creating DataTable With Xml Data
public System.Data.DataTable CreateDataTableFromXml(string XmlFile)
{
System.Data.DataTable Dt = new System.Data.DataTable();
try
{
DataSet ds = new DataSet();
ds.ReadXml(XmlFile);
Dt.Load(ds.CreateDataReader());
}
catch (Exception ex)
{
}
return Dt;
}
private void ExportDataTableToExcel(System.Data.DataTable table, string Xlfile)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook book = excel.Application.Workbooks.Add(Type.Missing);
excel.Visible = false;
excel.DisplayAlerts = false;
Worksheet excelWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
excelWorkSheet.Name = table.TableName;
progressBar1.Maximum = table.Columns.Count;
for (int i = 1; i < table.Columns.Count + 1; i++) // Creating Header Column In Excel
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
if (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.Value++;
int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new System.Drawing.Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
System.Windows.Forms.Application.DoEvents();
}
}
progressBar1.Maximum = table.Rows.Count;
for (int j = 0; j < table.Rows.Count; j++) // Exporting Rows in Excel
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
if (progressBar1.Value < progressBar1.Maximum)
{
progressBar1.Value++;
int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new System.Drawing.Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
System.Windows.Forms.Application.DoEvents();
}
}
book.SaveAs(Xlfile);
book.Close(true);
excel.Quit();
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(excel);
}
}
Is there any other method I can use?
The code below uses oledb to write a new excel file with values from the xml. It uses xml linq to parse the xml file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;
using System.IO;
namespace ConsoleApplication31
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
const string XML_FILENAME = #"c:\temp\text.xls";
const string SHEET_NAME = "sheet1";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("ContentDate", typeof(DateTime));
dt.Columns.Add("Originator", typeof(int));
dt.Columns.Add("FileContent", typeof(string));
dt.Columns.Add("RecordCount", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("OtherEntityName", typeof(string));
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("EntityID", typeof(string));
dt.Columns.Add("FirstAddressLine", typeof(string));
dt.Columns.Add("AddressNumber", typeof(string));
dt.Columns.Add("AdditionalAddressLine", typeof(string));
dt.Columns.Add("City", typeof(string));
dt.Columns.Add("Region", typeof(string));
dt.Columns.Add("Country", typeof(string));
dt.Columns.Add("PostalCode", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
XElement body = root.Element(ns + "Header");
DateTime contentDate = (DateTime)body.Element(ns + "ContentDate");
int originator = (int)body.Element(ns + "Originator");
string fileContent = (string)body.Element(ns + "FileContent");
int recordCount = (int)body.Element(ns + "RecordCount");
List<XElement> records = root.Descendants(ns + "Records").FirstOrDefault().Elements().ToList();
foreach (XElement record in records)
{
XElement entity = record.Element(ns + "Entity");
XElement confirmation = entity.Element(ns + "Confirmation");
string id = (string)confirmation.Element(ns + "ID");
string entityID = (string)confirmation.Element(ns + "EntityID");
foreach (XElement address in entity.Elements().Where(x => x.Name.LocalName.Contains("Address")))
{
DataRow newRow = dt.Rows.Add();
newRow["ContentDate"] = contentDate;
newRow["Originator"] = originator;
newRow["FileContent"] = fileContent;
newRow["RecordCount"] = recordCount;
newRow["ID"] = id;
newRow["EntityID"] = entityID;
newRow["Name"] = (string)entity.Element(ns + "Name");
newRow["OtherEntityName"] = string.Join(",", entity.Descendants(ns + "OtherEntityName").Select(x => (string)x));
XElement xAddress = address;
if (xAddress.Name.LocalName == "OtherAddresses") xAddress = address.Element(ns + "OtherAddress");
newRow["FirstAddressLine"] = (string)xAddress.Element(ns + "FirstAddressLine");
newRow["AddressNumber"] = (string)xAddress.Element(ns + "FirstAddressLine");
newRow["AdditionalAddressLine"] = string.Join(",", xAddress.Elements(ns + "FirstAddressLine").Select(x => (string)x));
newRow["City"] = (string)xAddress.Element(ns + "City");
newRow["Region"] = (string)xAddress.Element(ns + "Region");
newRow["Country"] = (string)xAddress.Element(ns + "Country");
newRow["PostalCode"] = (string)xAddress.Element(ns + "PostalCode");
}
}
if(File.Exists(XML_FILENAME)) File.Delete(XML_FILENAME);
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string connectionString = string.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Mode=ReadWrite;Extended Properties='Excel 8.0;HDR=Yes;IMEX=0';", XML_FILENAME);
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
Boolean firstRow = true;
string[] columnNames = dt.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
cmd = new OleDbCommand();
cmd.Connection = conn;
string dataType = "";
foreach (DataColumn dc in dt.Columns)
{
switch (dc.DataType.Name)
{
case "Int32" :
dataType = "integer";
break;
default:
dataType = dc.DataType.Name;
break;
}
if (firstRow)
{
string query = string.Format("CREATE TABLE [{0}] ( [{1}] {2})", SHEET_NAME, dc.ColumnName, dataType);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
firstRow = false;
}
else
{
string query = string.Format("Alter TABLE [{0}] ADD [{1}] {2}", SHEET_NAME, dc.ColumnName, dataType);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
}
string insertQuery = string.Format("INSERT INTO [{0}] ({1}) VALUES ({2});", SHEET_NAME, string.Join(",", columnNames), string.Join(",", dt.Columns.Cast<DataColumn>().Select(x => "#" + x.ColumnName)));
cmd.CommandText = insertQuery;
foreach (DataRow row in dt.AsEnumerable())
{
for(int colNumber = 0; colNumber < dt.Columns.Count; colNumber++)
{
cmd.Parameters.AddWithValue("#" + dt.Columns[colNumber].ColumnName, row[colNumber].ToString());
}
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
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.
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 use autopost in itemtemplate, but it do not update the result column immediately
i guess to use multiplier_dropdownlist_SelectedIndexChanged to update gridview, but
there is no gridview.update(); how to update displayed result immediately
[Solved]
protected void Timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i < Calculator_GridView.Rows.Count; i++)
{
string serial_no = Calculator_GridView.Rows[i].Cells[1].Text;
string a1_textbox = Calculator_GridView.Rows[i].Cells[2].Text;
string b1_textbox = Calculator_GridView.Rows[i].Cells[3].Text;
DropDownList mp_dropdown = (DropDownList)Calculator_GridView.Rows[i].Cells[4].Controls[1];
//TextBox Result_textbox = (TextBox)Calculator_GridView.Rows[e.RowIndex].Cells[5].Controls[0];
string executestring = "";
executestring = "Update cal set a1=" + a1_textbox;
executestring = executestring + ", b1=" + b1_textbox;
executestring = executestring + ", mp=" + mp_dropdown.SelectedValue;
executestring = executestring + ", result=" + (Convert.ToDouble(mp_dropdown.SelectedValue) * Convert.ToDouble(b1_textbox)).ToString();
executestring = executestring + " where [識別碼]=" + serial_no;
ExecuteDatabase(executestring);
}
string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|/db1.mdb";
OleDbConnection conn = new OleDbConnection(connstr);
conn.ConnectionString = connstr;
try
{
conn.Open();
}
catch (Exception ex)
{
conn.Close();
}
OleDbCommand get_info_cmd = null;
get_info_cmd = new OleDbCommand("SELECT [識別碼], [a1], [b1], [result], [mp] FROM [cal]", conn);
OleDbDataReader get_info_Reader = get_info_cmd.ExecuteReader();
store.Columns.Add(new DataColumn("識別碼", typeof(int)));
store.Columns.Add(new DataColumn("a1", typeof(double)));
store.Columns.Add(new DataColumn("b1", typeof(double)));
store.Columns.Add(new DataColumn("mp", typeof(double)));
store.Columns.Add(new DataColumn("result", typeof(double)));
DataRow dr;
try
{
while (get_info_Reader.Read())
{
dr = store.NewRow();
dr[0] = get_info_Reader["識別碼"].ToString();
dr[1] = get_info_Reader["a1"].ToString();
dr[2] = get_info_Reader["b1"].ToString();
dr[3] = get_info_Reader["mp"].ToString();
dr[4] = (Convert.ToDouble(get_info_Reader["b1"].ToString()) * Convert.ToDouble(get_info_Reader["mp"].ToString())).ToString();
store.Rows.Add(dr);
}
}
catch (Exception ex)
{
Error_Label.Text = Error_Label.Text + ex.ToString();
conn.Close();
}
finally
{
get_info_cmd.Dispose();
get_info_Reader.Close();
conn.Close();
}
storeview = new DataView(store);
Calculator_GridView.Font.Size = new FontUnit(10);
Calculator_GridView.DataSourceID = "";
Calculator_GridView.DataSource = storeview;
Calculator_GridView.DataBind();
}
keep the gridview inside an ajax update panel.after the content template of ajax control pane use a timer control which will periodically update ur gridview automatically