Gridview Using ObjectDataSource - not displaying info - c#

I've been unsuccessfully trying to bind a gridview through a web service, but nothing's showing up. Is there something wrong with my web method?
Here are what I have in my App_Code folder: membershipService.cs, DataAccessService.cs, Post.cs
membershipService.cs:
[WebMethod(Description = "Display all users' post")]
public Post[] DisplayAllPosts()
{
List<Post> usersPosts = new List<Post>();
DataSet ds;
Post p;
try
{
ds = DataAccessService.RunSimpleQuery("SELECT username, post, postDateTime FROM UserPosts ORDER BY postID DESC");
foreach (DataRow dr in ds.Tables[0].Rows)
{
p = new Post();
p.username = dr["username"].ToString();
p.post = dr["post"].ToString();
p.postDateTime = dr["postDateTime"].ToString();
usersPosts.Add(p);
}
return usersPosts.ToArray();
}
catch (Exception ex)
{
return null;
}
}
DataAccessService.cs:
public static DataSet RunSimpleQuery(string query)
{
DataSet result = new DataSet();
OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDb.OleDbCommand command;
OleDb.OleDbDataAdapter dataAdapter;
try
{
//open database connection
connection.Open();
//create database command for query
command = new OleDb.OleDbCommand();
command.CommandText = query;
command.Connection = connection;
command.CommandType = CommandType.Text;
//create data adapter and use it to fill the data set using the command
dataAdapter = new OleDb.OleDbDataAdapter();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(result);
}
catch
{
result = null;
}
finally
{
//close connection
connection.Close();
connection.Dispose();
}
//return dataset
return result;
}
Post.cs:
public class Post
{
public string username;
public string post;
public string postDateTime;
}
I'll appreciate any help I can get. Thank you!

have you tried putting a breakpoint on the exception handler in DisplayAllPosts to see if an exception is being thrown there?
Unless all of your database columns are non-nullable, you could have a DbNull.Value in one of your columns that is throwing an exception.

Related

Load data from database to string

I'm trying at the moment to get an information from a database and want to save it in a string, but yeah not sure about how really to do it right.
This is my code, where I open the LoadSql function:
public void LoadData(string KNR, string WNR, String filter)
{
// WHERE
const string sqlTemplate = "SELECT KUNDENAUFTRAGSNR FROM MESSFELD.AUSSTANDSDATEN WHERE FTNR = '" + txt_Barcode_read.Text + "'";
string sql = string.Format(sqlTemplate, filter);
Database cdb = new Database();
// try to connect and cancel on error
if (!cdb.Open("**********", "*********"))
{
SetStatusText("Datenbank ist nicht verfügbar.");
return;
}
WNR = cdb.LoadSql(sql);
cdb.Close();
}
And here is the LoadSQL function:
public DataTable LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
catch
{
return null;
}
}
For the moment the LoadSQL is saving in datatable, how to change for saving the number in the string WNR?
You can re-write your LoadSQL function to something like this :
public string LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
rdr.Read();
if(rdr.HasRows)
return rdr.GetString(0);
else
return "";
}
catch
{
return null;
}
}

I have treeNode view Code How To convert it for Recursive Function

I have a code well functioning and working to increase it functionality and make a code I thought using recursive function would be great I have tree view node
code when i tried to make this to recursive function it does not show it will display a empty box Here is my normal code
public string ParentNode_Query = #"Select COMPONENT_NAME
from Table
where PARENT_NAME is null";
public string Rest_of__Node_Query = #"Select COMPONENT_NAME
from Table
where
PARENT_NAME=#Parentname";
public Task Populate_Tree_View(TreeView treeView)
{
try
{
SqlCommand new1 = new SqlCommand(#"select COMPONENT_NAME from bom", Connection);
var data = Table.dataTable_Create_Method(new1);
while (true) {
SqlCommand = new SqlCommand(Database_Query.ParentNode_Query, Connection);
var data_Parent = Table.dataTable_Create_Method(SqlCommand);
foreach (DataRow frist in data_Parent.Rows)
{
Parent_Node = new TreeNode(frist["COMPONENT_NAME"].ToString());
SqlCommand = new SqlCommand(Database_Query.Rest_of__Node_Query, Connection);
SqlCommand.Parameters.AddWithValue("#Parentname", frist["COMPONENT_NAME"].ToString());
// These Variable are created purpose are for clean and readble code
var data_Second_Node = Table.dataTable_Create_Method(SqlCommand);
foreach (DataRow second in data_Second_Node.Rows)
{
Second_Node = new TreeNode(second["COMPONENT_NAME"].ToString());
Parent_Node.Nodes.Add(Second_Node);
SqlCommand = new SqlCommand(Database_Query.Rest_of__Node_Query, Connection);
SqlCommand.Parameters.AddWithValue("#Parentname", second["COMPONENT_NAME"].ToString());
var data_Third_Node = Table.dataTable_Create_Method(SqlCommand);
foreach (DataRow third in data_Third_Node.Rows)
{
Third_Node = new TreeNode(third["COMPONENT_NAME"].ToString());
Second_Node.Nodes.Add(Third_Node);
SqlCommand = new SqlCommand(Database_Query.Rest_of__Node_Query, Connection);
SqlCommand.Parameters.AddWithValue("#Parentname", third["COMPONENT_NAME"].ToString());
var data_Fourth_Node = Table.dataTable_Create_Method(SqlCommand);
foreach (DataRow fourth in data_Fourth_Node.Rows)
{
Fourth_Node = new TreeNode(fourth["COMPONENT_NAME"].ToString());
Third_Node.Nodes.Add(Fourth_Node);
SqlCommand = new SqlCommand(Database_Query.Rest_of__Node_Query, Connection);
SqlCommand.Parameters.AddWithValue("#Parentname", fourth["COMPONENT_NAME"].ToString());
var data_Fifth_Node = Table.dataTable_Create_Method(SqlCommand);
foreach (DataRow five in data_Fifth_Node.Rows)
{
Fifth_Node = new TreeNode(five["COMPONENT_NAME"].ToString());
Fourth_Node.Nodes.Add(Fifth_Node);
}
}
}
}
}
treeView.Nodes.Add(Parent_Node); }
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return Task.CompletedTask;
}
public class DataTableCreation
{
private SqlDataAdapter sqlDataAdapter;
// use this method to Create a Datatable and fill it with data
public DataTable dataTable_Create_Method(SqlCommand sqlCommand)
{
sqlDataAdapter = new SqlDataAdapter(sqlCommand);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
return dataTable;
}
}
As you can see the similar method is repeating all over the places to reduce this i thought recursive is good. But i tried diffrent way from internet i does not work. Another Problem is the table does not contain any Id field so I have to filter them using Component name also I need this function to use if i alter the database also. Is this possible to do in recursive is that so how to this
Something like this, but you'll need to run it and debug it.
public Task Populate_Tree_View(TreeView treeView)
{
try
{
SqlCommand new1 = new SqlCommand(#"select COMPONENT_NAME from bom", Connection);
var data = Table.dataTable_Create_Method(new1);
var SqlCommand = new SqlCommand(Database_Query.ParentNode_Query, Connection);
var data_Parent = Table.dataTable_Create_Method(SqlCommand);
PopulateRows(treeView.Nodes, data_Parent);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, MediaTypeNames.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return Task.CompletedTask;
}
public static void PopulateRows(TreeNodeCollection nodesCollection, DataTable rowsData)
{
foreach (DataRow child in rowsData.Rows)
{
var thisNode = new TreeNode(child["COMPONENT_NAME"].ToString());
nodesCollection.Add(thisNode);
var sqlCommand = new SqlCommand(Database_Query.Rest_of__Node_Query, Connection);
sqlCommand.Parameters.AddWithValue("#Parentname", child["COMPONENT_NAME"].ToString());
var dataChildNode = Table.dataTable_Create_Method(sqlCommand);
PopulateRows(thisNode.Nodes, dataChildNode);
}
}

C# asp.NET displaying output of a query to screen. Error: 'System.ArgumentException' in Oracle.DataAccess.dll

First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}

Passing Connection From TableAdapter Produces connectionstring property has not been initialized

I ran into a problem where passing a connection from a TableAdapter to some methods throws an exception stating the connectionstring isn't initialized. There are quite a few questions on SO with this exception but none were passing the connection and most were because the ConnectionString was null. Weird thing is I used MessageBox.Show(connection.ConnectionString); through out the chain of methods and I receive a valid connection string at every step. This is a somewhat complicated program that is in production but I will try to simplify the code for this question...
This is the postInventoryData method, which takes a DataGridView with inventory items and iterates through it posting them to the inventory. I use a TransactionScope to ensure the changes are safely rolled back in the event of an error. If an item is a kit(an item comprised of other items) I must iterate through those items and remove them from the inventory. The problem occurs when I check whether or not the item is a kit.
public bool postInventoryData(DataGridView dgv)
{
bool successful = true;
TestDataSetTableAdapters.inentoryTrxTableAdapter inventoryTrxAdapter =
new TestDataSetTableAdapters.inentoryTrxTableAdapter();
try
{
using (TransactionScope trxScope = new TransactionScope
(TransactionScopeOption.Required, new System.TimeSpan(0, 15, 0)))
{
MessageBox.Show(inventoryTrxAdapter.Connection.ConnectionString); // <-- Valid ConnectionString
inventoryTrxAdapter.OpenConnection();
for (int i = 0; i < dgv.Rows.Count; i++)
{
//parameter values
string departmentCode = dgv.Rows[i].Cells["Department_Code"].Value.ToString();
string machineCode = dgv.Rows[i].Cells["Machine_Code"].Value.ToString();
string operatorCode = dgv.Rows[i].Cells["Operator_Code"].Value.ToString();
string itemNumber = dgv.Rows[i].Cells["Item_Number"].Value.ToString();
double? qtyProduced = Convert.ToDouble(dgv.Rows[i].Cells["Quantity"].Value.ToString());
bool isKit =
businessLayer.isItemNumberKit
(inventoryTrxAdapter.Connection, itemNumber); // <-- CULPRIT!
// Inserts the item
dailyProductionInsertQty(
departmentCode,
machineCode,
operatorCode,
itemNumber,
isKit,
qtyProduced,
inventoryTrxAdapter,
trxScope);
}
inventoryTrxAdapter.CloseConnection();
trxScope.Complete();
}
}
catch (System.Exception ex)
{
successful = false;
MessageBox.Show(ex.ToString());
}
return successful;
}
The isItemNumberKit method
public bool isItemNumberKit(SqlConnection connection, string itemNumber)
{
bool contains;
MessageBox.Show(connection.ConnectionString); // <-- Valid ConnectionString
DataTable dt = getKit(connection, itemNumber); // <-- CULPRIT!
if (dt.Rows.Count > 0)
{
contains = true;
}
else
{
contains = false;
}
return contains;
}
The getKit method
public DataTable getKit(SqlConnection connection, string itemNumber)
{
DataTable dt = new DataTable();
SqlConnection myConnection = connection;
MessageBox.Show(myConnection.ConnectionString); // <-- Valid ConnectionString
SqlParameter paramItemNumber = new SqlParameter();
paramItemNumber.ParameterName = "#ItemNumber";
paramItemNumber.Value = itemNumber;
paramItemNumber.SqlDbType = System.Data.SqlDbType.VarChar;
try
{
using (myConnection)
{
string sql =
#"SELECT kits.Row_Id,
kits.Kit_Item_Number,
kits.Location_Code
FROM Inventory.dbo.Z_PV_Kits kits
WHERE kits.Kit_Item_Number=#ItemNumber";
//myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myCommand.Parameters.Add(paramItemNumber);
SqlDataReader reader = myCommand.ExecuteReader();
dt.Load(reader);
}
}
}
catch (Exception ex)
{
dt = null;
MessageBox.Show(ex.ToString());
}
return dt;
}
When I execute postInventoryData the program throws an exception with the message, "The connectionstring property has not been initialized." with the line numbers pointing to isItemNumberKit and getKit. As you can see in the code above, I used a MessageBox.Show(connection.ConnectionString) throughout the process and each time I received a valid Connection string. I have created a workaround which stores a cached DataTable containing all the kit items I can run linq statements on. I am not in emergency mode or anything but I thought this to be weird and an opportunity for me to learn. Thanks in advance for any help!
It might be possible that you have 2 app.config files in your solution with 2 different connection strings.
OK, I figured it out and now when I think about it the answer was somewhat obvious. I always use using(){} blocks to ensure connections and similar objects are properly disposed and taken care of after they are used. The solution was to simply remove the using(myConnection){} block from the getKit method like this:
public DataTable getKit(SqlConnection connection, string itemNumber)
{
DataTable dt = new DataTable();
SqlConnection myConnection = connection;
MessageBox.Show(myConnection.ConnectionString);
SqlParameter paramItemNumber = new SqlParameter();
paramItemNumber.ParameterName = "#ItemNumber";
paramItemNumber.Value = itemNumber;
paramItemNumber.SqlDbType = System.Data.SqlDbType.VarChar;
try
{
string sql =
#"SELECT kits.Row_Id,
kits.Kit_Item_Number,
kits.Location_Code
FROM Inventory.dbo.Z_PV_Kits kits
WHERE kits.Kit_Item_Number=#ItemNumber
";
//myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myCommand.Parameters.Add(paramItemNumber);
SqlDataReader reader = myCommand.ExecuteReader();
dt.Load(reader);
}
}
catch (Exception ex)
{
dt = null;
MessageBox.Show(ex.ToString());
}
return dt;
}
This will leave the connection intact but properly dispose of the command. Sorry for the long winded question with a short simple answer. Hope this might help someone someday.

Filling a DataTable in C# using MySQL

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

Categories

Resources