I'm new to C#. I'm having a difficult time displaying my Access data in a DataTable. Here is the code:
try
{
reader.Read();
for (int i = 0; i < 16; i++)
{
if (selectedCourse == reader["CourseName"].ToString())
{
match = true;
}
else
{
match = false;
}
}
if (match == true)
{
tabControl.SelectedTab = tabPage1; // opens results page
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\...454_Database.accdb";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("Select c.PeriodID, c.CourseName, c.Teacher, t.Room"
+ "FROM Courses c JOIN Teacher t ON t.TeacherID = c.TeacherID"
+ "WHERE [CourseName] ='" + cboxClass.Text + "'", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataTblResults.DataSource = results;
I can tell the data is being compared to the db and it correctly determines if the query has results or not. However, when there are results, they do not get displayed on the data table. Is it because it doesn't know which columns correspond to the columns in the data table?
Thanks in advance!
How is your datagrid configured?
Try setting: (before setting the DataSource)
dataTblResults.AutoGenerateColumns = true;
dataTblResults.DockStyle.Fill = DockStyle.Fill;
Try using a Dataset first. Then turn it to a datatable
DataSet ds = new DataSet();
adapter.fill(ds)
if (ds.Tables[0].Rows.Count >= 1)
{
results = ds.Tables[0];
}
dataTblResults.DataSource = results;
I dont think this is what you are looking for but maybe it'll bring you closer to the answer
Related
I am creating a program that I will allow you to enter in a number and it will display the information in the respective row. However, if the number is not found in the num field, I want it to return with showing the text I set for a label (label12). However, I am getting returned with exception errors and I cannot figure out how to create this where if the num doesn't exist it will perform a set action.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
oda.Fill(dt);
if (oda.Fill(dt).Equals(null))
{
label12.Show();
}
else if (!oda.Fill(dt).Equals(textBox11.Text))
{
textBox1.Text = dt.Rows[0][1].ToString();
textBox2.Text = dt.Rows[0][2].ToString();
textBox3.Text = dt.Rows[0][3].ToString();
textBox4.Text = dt.Rows[0][4].ToString();
textBox5.Text = dt.Rows[0][5].ToString();
textBox6.Text = dt.Rows[0][6].ToString();
textBox7.Text = dt.Rows[0][7].ToString();
textBox8.Text = dt.Rows[0][8].ToString();
textBox9.Text = dt.Rows[0][9].ToString();
textBox10.Text = dt.Rows[0][10].ToString();
bool v = String.IsNullOrEmpty(dt.Rows[0][11].ToString());
if (!v)
{
pictureBox1.Load(dt.Rows[0][11].ToString());
}
else
{
pictureBox1.Load(dt.Rows[0][12].ToString());
}
}
The result of the Fill() method is the number of rows returned. Just update your code to check the result of Fill() is greater than zero records.
olcn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\TestUser\Documents\testlist.mdb");
OleDbDataAdapter oda = new OleDbDataAdapter("select * from testlist where num = '"+textBox11.Text+"'", olcn);
DataTable dt = new DataTable();
int count = oda.Fill(dt);
if (count == 0)
{
label12.Show();
}
else
{
// ... your mapping logic
}
MS Documentation, OleDbDataAdapter.Fill Method
A function in my app is returning a data table by joining the data tables getting from many other sub functions. Each sub functions are independent to each other with common primary key. Now, It takes nearly two minutes to execute the function for 50 of students. Please suggest me a best/fastest way to achieve the same.
public DataTable ShowReportOnGridivew(int class_id, string searchDate)
{
DataTable dt_students_List = null;
try
{
//====Main Table=====//
dt_students_List = GetDistinctStudentList(class_id);//there will be around minimum of 50 students
if (dt_students_List != null)
dt_students_List.PrimaryKey = new DataColumn[] { dt_students_List.Columns["student_id"] };
//Tables need to merge with main table
DataTable dt_CurrentRank = null;
DataTable dt_ScoreInEnglish = null;
DataTable dt_AcademicDetails = null;
DataTable dt_ExtraCurriculam = null;
DataTable dt_Attendance = null;
DataTable dt_Arts = null;
DataTable dt_FuelToBridger = null;
DataTable dt_FuelToAircraft = null;
DataTable dt_TeacherFeedback = null;
DataTable dt_TotalScore = null;
foreach (DataRow row in dt_students_List.Rows)
{
string student_id = row["student_id"].ToString();//primary key
//==========Current Rank================//
dt_CurrentRank = GetCurrentRank(student_id);//Binding data using sql
dt_CurrentRank.PrimaryKey = new DataColumn[] { dt_CurrentRank.Columns["student_id"] };
if (dt_CurrentRank != null)
{
dt_students_List.Merge(dt_CurrentRank);
}
//====== Score in English =====
dt_ScoreInEnglish = GetScoreInEnglish(student_id, searchDate);
dt_ScoreInEnglish.PrimaryKey = new DataColumn[] { dt_ScoreInEnglish.Columns["student_id"] };
if (dt_ScoreInEnglish != null)
{
dt_students_List.Merge(dt_ScoreInEnglish);
}
//====== Academic Details =====
dt_AcademicDetails= GetAcademicDetails(student_id);
dt_AcademicDetails.PrimaryKey = new DataColumn[] { dt_AcademicDetails.Columns["student_id"] };
if (ddt_AcademicDetails != null)
{
dt_students_List.Merge(dt_AcademicDetails);
}
//=====Similarly calling other functions and merging the columns to dt_students_List ======
}
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("StudentsList", log_data);
throw show_error;
}
return dt_students_List;
}
====== Each sub functions are written like below.=============
private async DataTable GetCurrentRank(string student_id)
{
DataTable dt = null;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = null;
SqlDataReader dr = null;
string sql = string.Empty;
sql = "SELECT student_id,current_rank FROM student_details WHERE " +
" student_id = #student_id ";
cmd = new SqlCommand(sql, con);
con.Open();
try
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#student_id", student_id);
dr = cmd.ExecuteReader();
dt = new DataTable("CurrentRank");
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("student_id", typeof(int)),
new DataColumn("current_rank", typeof(float))});
if (dr.HasRows)
{
dt.Load(dr);
}
string log_data = "Web App Function: GetCurrentRank \n";
log_data += "Response: " + JsonConvert.SerializeObject(dt);
obj.DatalogFile("GetCurrentRank", log_data);
return dt;
}
catch (Exception show_error)
{
string log_data = "Response: Error- " + show_error.ToString();
obj.DatalogFile("GetCurrentRank", log_data);
throw show_error;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
You can write multiple select statement in single stored procedure;
and get output in DataSet.
You can get all your tables in a single request:
CREATE PROCEDURE Demo
**Parameters**
AS
-- Your all functions select statements
GO;
C#:
public DataSet GetDataSet(string ConnectionString, string SpName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SpName;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
I am getting data from excel and showing it in DataGridWiew.
I have two textboxes, one is for starting index for first record and other is for last record.
Code works fine. But lets suppose starting record is 1 and ending is 10 when I change 10 to 1 or 2 it gives me an error in this line:
adapter.Fill(dataTable);
Full Code is below:
public DataSet Parse(string fileName)
{
string connectionString = string.Format("provider = Microsoft.Jet.OLEDB.4.0; data source = {0}; Extended Properties = Excel 8.0;", fileName);
DataSet data = new DataSet();
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string query = "";
var dataTable = new DataTable();
if(tbStarting.Text.Trim()=="" && tbEnding.Text.Trim() == "")
{
query = string.Format("SELECT * FROM [{0}]", sheetName);
}
else
{
query = string.Format("SELECT * FROM [{0}] where SrNo between " + int.Parse(tbStarting.Text.Trim()) + " and " + int.Parse(tbEnding.Text.Trim()) + " order by SrNo", sheetName);
}
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
con.Close();
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}
Why this is happening please help me?
Looking at the code, it seems that your procedure is working when you ask to retrieve all the record in each table. But you are not showing which table (Sheet) is actually used afterwars.
Chances are, you are using the first one only.
When you submit some parameters, only one of the tables (Sheets) can fulfill those requirements. The other(s) don't, possibly because a field named [SrNo] is not present.
This causes the More Parameters Required error when trying to apply a filter.
Not related to the error, but worth noting: you don't need to recreate the whole DataSet + DataTables to filter your DataSources.
The DataSet.Tables[N].DefaultView.RowFilter can be used to get the same result without destroying all the objects each time a filter is required.
RowFilter has some limitations in the language (e.g. does not support BETWEEN, Field >= Value1 AND Field <= Value2 must be used), but it's quite effective.
This is a possible setup:
(xDataSet is a placeholder for your actual DataSet)
//Collect the values in the TextBoxes in a string array
private void button1_Click(object sender, EventArgs e)
{
string[] Ranges = new string[] { tbStarting.Text.Trim(), tbEnding.Text.Trim() };
if (xDataSet != null)
FilterDataset(Ranges);
}
private void FilterDataset(string[] Ranges)
{
if (string.IsNullOrEmpty(Ranges[0]) & string.IsNullOrEmpty(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = null;
else if (string.IsNullOrEmpty(Ranges[0]) | string.IsNullOrEmpty(Ranges[1]))
return;
else if (int.Parse(Ranges[0]) < int.Parse(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo >= {0} AND SrNo <= {1}", Ranges[0], Ranges[1]);
else
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo = {0}", Ranges[0]);
this.dataGridView1.Update();
}
I've modified your code you code a bit to handle those requirements.
(I've left here those filters anyway; they're not used, but if you still want them, they are in a working condition)
DataSet xDataSet = new DataSet();
string WorkBookPath = #"[Excel WorkBook Path]";
//Query one Sheet only. More can be added if necessary
string[] WBSheetsNames = new string[] { "Sheet1" };
//Open the Excel document and assign the DataSource to a dataGridView
xDataSet = Parse(WorkBookPath, WBSheetsNames, null);
dataGridView1.DataSource = xDataSet.Tables[0];
dataGridView1.Refresh();
public DataSet Parse(string fileName, string[] WorkSheets, string[] ranges)
{
if (!File.Exists(fileName)) return null;
string connectionString = string.Format("provider = Microsoft.ACE.OLEDB.12.0; " +
"data source = {0}; " +
"Extended Properties = \"Excel 12.0;HDR=YES\"",
fileName);
DataSet data = new DataSet();
string query = string.Empty;
foreach (string sheetName in GetExcelSheetNames(connectionString))
{
foreach (string WorkSheet in WorkSheets)
if (sheetName == (WorkSheet + "$"))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
DataTable dataTable = new DataTable();
if ((ranges == null) ||
(string.IsNullOrEmpty(ranges[0]) || string.IsNullOrEmpty(ranges[1])) ||
(int.Parse(ranges[0]) > int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}]", sheetName);
else if ((int.Parse(ranges[0]) == int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}] WHERE SrNo = {1}", sheetName, ranges[0]);
else
query = string.Format("SELECT * FROM [{0}] WHERE (SrNo BETWEEN {1} AND {2}) " +
"ORDER BY SrNo", sheetName, ranges[0], ranges[1]);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
};
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
string[] excelSheetNames = null;
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
if (dt != null)
{
excelSheetNames = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
excelSheetNames[i] = dt.Rows[i]["TABLE_NAME"].ToString();
}
}
}
}
return excelSheetNames;
}
This is my second question here in StackOverflow and this is where im stuck
i want to loop every value in a multiline textbox and pass it as query criteria then fill my DataGridView with the result (multiple results).
The problem is. that i cannot pass more than 1 value from the textbox. i can execute correctly the query but its not looping correctly as it only shows the result of the first value in my data grid and i want the data(result) from every line in the textbox
my code is
for (int i = 0; i < textBox1.Lines.Length; i++)
{
Connect();
OracleCommand cmd = new OracleCommand();
OracleDataAdapter adapter = new OracleDataAdapter();
DataTable dt = new DataTable();
cmd = new OracleCommand(OraSql + OraSql2 + orasql3 + OraSql4, con);
adapter = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
adapter.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dataGridView1.Rows.Add
(
row[0].ToString(),
row[1].ToString(),
row[2].ToString(),
row[3].ToString(),
row[4].ToString(),
row[5].ToString()
);
}
}
i hope that i explained myself correctly here
Thank you!
this is my query
string OraSql = #"SELECT r.ixkitl ""Parent Part Number"",
r.ixlitm ""Component Part Number"",
i.imdsc1 ""Description"",
SUM((r.ixqnty/10000)) ""Qty per Harness"",
To_date(r.ixefff+1900000, 'YYYYDDD') ""Effective From Date"",
To_date(r.ixefft+1900000, 'YYYYDDD') ""Effective Thru Date"",
r.ixtbm ""Bill Type"",
r.ixmmcu ""Branch Plt""
FROM proddta.f3002 r,
proddta.f4101 i";
string OraSql2 = #"
WHERE (i.imlitm IN '" + textBoxX1.Text.ToString() + "'AND i.imitm = r.ixkit)";
string orasql3 = #"
AND (r.ixmmcu = ' 3320' AND r.ixtbm = 'M ')";
string OraSql4 = #"
AND r.ixefff <= (to_char(SYSDATE, 'YYYYDDD')-1900000)
AND r.ixefft >= (to_char(SYSDATE, 'YYYYDDD')-1900000)
GROUP BY r.ixkitl,
r.ixlitm,
r.ixqnty,
r.ixtbm,
r.ixmmcu,
r.ixefff,
r.ixefft,
i.imdsc1
ORDER BY r.ixkitl,
r.ixlitm";
I'm attempting to fill a DataTable with results pulled from a MySQL database, however the DataTable, although it is initialised, doesn't populate. I wanted to use this DataTable to fill a ListView. Here's what I've got for the setting of the DataTable:
public DataTable SelectCharacters(string loginName)
{
this.Initialise();
string connection = "0.0.0.0";
string query = "SELECT * FROM characters WHERE _SteamName = '" + loginName + "'";
if (this.OpenConnection() == true)
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
}
else
{
this.CloseConnection();
DataTable dt = new DataTable("CharacterInfo");
return dt;
}
}
And for the filling of the ListView, I've got:
private void button1_Click(object sender, EventArgs e)
{
string searchCriteria = textBox1.Text;
dt = characterDatabase.SelectCharacters(searchCriteria);
MessageBox.Show(dt.ToString());
listView1.View = View.Details;
ListViewItem iItem;
foreach (DataRow row in dt.Rows)
{
iItem = new ListViewItem();
for (int i = 0; i < row.ItemArray.Length; i++)
{
if (i == 0)
iItem.Text = row.ItemArray[i].ToString();
else
iItem.SubItems.Add(row.ItemArray[i].ToString());
}
listView1.Items.Add(iItem);
}
}
Is there something I'm missing? The MessageBox was included so I could see if it has populated, to no luck.
Thanks for any help you can give.
Check your connection string and instead of using
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataAdapter returnVal = new MySqlDataAdapter(query,connection);
DataTable dt = new DataTable("CharacterInfo");
returnVal.Fill(dt);
this.CloseConnection();
return dt;
you can use this one
MySqlCommand cmd = new MySqlCommand(query, connection);
DataTable dt = new DataTable();
dt.load(cmd.ExecuteReader());
return dt;
Well, I ... can't figure out what you have done here so I'll paste you my code with which I'm filling datagridview:
1) Connection should look something like this(if localhost is your server, else, IP adress of server machine):
string connection = #"server=localhost;uid=root;password=*******;database=*******;port=3306;charset=utf8";
2) Query is ok(it will return you something), but you shouldn't build SQL statements like that.. use parameters instead. See SQL injection.
3) Code:
void SelectAllFrom(string query, DataGridView dgv)
{
_dataTable.Clear();
try
{
_conn = new MySqlConnection(connection);
_conn.Open();
_cmd = new MySqlCommand
{
Connection = _conn,
CommandText = query
};
_cmd.ExecuteNonQuery();
_da = new MySqlDataAdapter(_cmd);
_da.Fill(_dataTable);
_cb = new MySqlCommandBuilder(_da);
dgv.DataSource = _dataTable;
dgv.DataMember = _dataTable.TableName;
dgv.AutoResizeColumns();
_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (_conn != null) _conn.Close();
}
}
So, every time I want to display some content of table in mysql database I call this method, pass query string and datagridview name to that method. and, that is it.
For your sake, compare this example with your and see what can you use from both of it. Maybe, listview is not the best thing for you, just saying ...
hope that this will help you a little bit.
Debug your application and see if your sql statement/ connection string is correct and returns some value, also verify if your application is not throwing any exception.
Your connection string is invalid.
Set it as follows:
connection = "Server=myServer;Database=myDataBase;Uid=myUser;Pwd=myPassword;";
Refer: mysql connection strings
Here the following why the codes would not work.
Connection
The connection of your mySQL is invalid
Query
I guess do you want to search in the table, try this query
string query = "SELECT * FROM characters WHERE _SteamName LIKE '" + loginName + "%'";
notice the LIKE and % this could help to list all the data. for more details String Comparison Functions