conversion failed varchar to int - c#

Below is the code for combo box selected value change. It is supposed to pick up a value from DB and display it in a text box.
protected void cmbPujaName_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con2 = null;
con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SRKBSDB"].ConnectionString);
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName =" + cmbPujaName.SelectedValue, con2);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds); ......... Error shown here...........
txtAmount.Text = pamtds.Tables[0].Rows[0]["Amount"].ToString();
}

You're missing quotes but... do not do that like this. This way is like leaving your door wide open and invite thieves inside for a tea party. Or SQL Injection attack, inviting hackers to steal your whole database and/or server and take full control over it.
Have such code instead:
SqlDataAdapter pamt = new SqlDataAdapter("select Amount from PoojaDietyMaster where PoojaName = #name", con2);
pamt.SelectCommand.Parameters.AddWithValue("#name", cmbPujaName.SelectedValue);
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);
This way you won't have to mess around with quotes, plus you're better protected against hackers.

It's a better practice to write a query using SqlCommand parameters by mentioning proper datatype to avoid sql injection attacks. Try to handle null values as well.
SqlDataAdapter pamt = new SqlDataAdapter("select Isnull(Amount,0.0) Amount from PoojaDietyMaster where PoojaName = #name", con2);
pamt.SelectCommand.Parameters.Add("#name",SqlDbType.VarChar).Value = cmbPujaName.SelectedValue.tostring();
DataSet pamtds = new DataSet();
pamt.Fill(pamtds);

Related

How to load the datagridview using OOP C#

I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.

Using sql tableadapters to update database C#

I am building an application for a group of friends and myself to use for DnD sessions. Part of the program involves taking all of the values that are entered for our characters, items, etc and storing them to a database. I have the database built, and am pulling from the database into the program, however I am unable to return data to the database. I have the data coming into a dataset, and all of my edits are affecting the dataset, but I cannot get anything to affect the actual source database tables.
Below I have the button that I intend to use to update items in the characters' packs. I have both dataadapter, and tableadapter methods included that I have tried.
private void btnaddpack_Click(object sender, EventArgs e)
{
if (txtbxpack.Text != "")
{
/*connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName)" + "WHERE Id = '" + this.lstpack.SelectedValue + "';";
cmd.ExecuteNonQuery();
cmd.Clone();*/
string packitem = txtbxpack.Text; //will take item from an textbox
this.packTableAdapter.Insert(packitem);
this.Validate();
this.packBindingSource.EndEdit();
this.packTableAdapter.Update(this.dnD_MachineDataSet.Pack);
}
PopulatePack();
Here is my populate code in case someone needs that:
private void PopulatePack()
{
using (connection = new SqlConnection(connectionString)) //this is all about opening the connection to the sqldatabase, normally it would need to be closed, but this uses idisposable, so it will close itself
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Pack", connection))
{
DataTable packtable = new DataTable();
adapter.Fill(packtable);
lstpack.DataSource = packtable;
lstpack.DisplayMember = "Item";
lstpack.ValueMember = "Id";
}
}
As mentioned above, all of the changes are appearing whenever I re-populate the listboxes that draw upon the dataset, hence why this is an issue of trying to get that data back into the source database. I will make the obligatory "I'm relatively new to using databases" statement as it will do no good to pretend that I am an expert.
Thanks.
In the commented code, you would need to do the following:
assign the connection object to the SqlCommand object's Connection
property
pass the item name to your #ItemName parameter
assign a parameter value to the 'Id' column in the WHERE clause
remove, 'cmd.Clone();', and replace with, 'connection.Close();'
Here is what the code should look like:
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "UPDATE Pack SET Item = (#ItemName) WHERE Id = #ID;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#ItemName", txtbxpack.Text);
cmd.Parameters.AddWithValue("#ID", this.lstpack.SelectedValue);
cmd.ExecuteNonQuery();
connection.Close();

Session variables being broken by an unrelated method

I have a problem that is completely boggling me as it makes absolutely no sense. Ok, as I understand and have used in the past, to pass variables from one page to another via session, you simply say
Session["variableName"] = value;
Then to use it in the receiving page, it something like:
string container = Session["variableName"].ToString();
Right? Dandy. In my code (at least this particular application, anyway), I'm find that I can't set any session variables if I have a method in my page_load of the code-behind:
protected void Page_Load(object sender, EventArgs e)
{
Session.Add("values", "It Worked");
LoadAvailableItems();
}
This will cause the application to not pass the variable to the next page. However, if I remove the LoadAvailableItems() method, it will work just fine. So now you'll ask me "ok, so show us whats inside of that method". It is just a test connection to run dummy data for a control:
//test connection DELETE ME
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ Server.MapPath("App_Code/temp/cokeDb.mdb") + ";Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connString);
string sql = "select docNum, docName from lut_docs order by docNum";
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
cblstAvailableItems.DataSource = ds;
cblstAvailableItems.DataTextField = "docName";
cblstAvailableItems.DataValueField = "docNum";
cblstAvailableItems.DataBind();
//end test connection
From what I was able to narrow it down to through commenting out blocks and running the application, I think it is related to this block:
conn.Open();
da.Fill(ds);
conn.Close();
Now WHY this is causing a problem, I do not understand in the slightest. If someone could explain this to me, I may refrain from putting my head through a wall.

Page Life Cycle, does db connection go in Page_Load

Currently I have The following code:
void Page_Load(object sender, System.EventArgs e)
{
string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
SqlConnection mySqlConnection = new SqlConnection(connectionString);
string procedureString = "Callin_Insert";
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = procedureString;
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.Add("#LVDate", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#LVTime", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#CuID", SqlDbType.Int).Value = CustID;
mySqlCommand.Parameters.Add("#Type", SqlDbType.Int).Value = Keypress;
mySqlConnection.Open();
mySqlCommand.ExecuteNonQuery();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
mySqlConnection.Close();
}
Basically, I am opening a connection to the Database during the page_load. I am also closing that connection in page_load. Part of my problem is that the CustID & Keypress are not getting passed, because they occur later in the page life cycle. What is the best way to open the connection, get the 2 variables (when I they are entered by the user), pass them to the database, and close the connection.
Somethings I have tried is running it _OnLoad. But this didn't work either.
Any thoughts or suggestion, are greatly appreciated.
First of SqlConnection is of IDisposible interface means it is much safer to wrap your code with using statement like this.
string connectionString = "server=abc;database=abc;uid=abc;pwd=1234";
using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
{
string procedureString = "Callin_Insert";
SqlCommand mySqlCommand = new SqlCommand(procedureString, mySqlConnection);
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.Add("#LVDate", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#LVTime", SqlDbType.DateTime).Value = DateTime.Now;
mySqlCommand.Parameters.Add("#CuID", SqlDbType.Int).Value = CustID;
mySqlCommand.Parameters.Add("#Type", SqlDbType.Int).Value = Keypress;
mySqlConnection.Open();
mySqlCommand.ExecuteNonQuery();
//i have no idea what does this mean, data adapter is for filling Datasets and DataTables
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;
}
Second of all i offer you to use SqlDataSourceObject control which will make much easier to work with cases like yours.
It will know how to deal with Page.IsPostBack that you haven't implemented but should, paging and other stuff you need.
Think there are a few problems here... first of all why are you running your query and then passing it to a data adapter? The data adapter will run the select command when queried.
I suggest creating a SqlDataSource on your aspx page (not code behind) and bind your control to it. Then hook up the Selecting event and in there populate your parameters. That should happen later in the page lifecycle so your parameter values will then be set.

c# windows forms / basic data grid

One of the problems I am having with c# is that there seems to be so much information online that I am having trouble finding the right answer to the most basic of questions.
I am trying to do something simple:
I have a button, I click it, it queries the database and populates a datagrid on my windows form.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection c = new SqlConnection("Data Source = (local); Integrated Security = true; Initial Catalog = pubs; ");
c.Open();
// 2
// Create new DataAdapter
SqlCommand cmd = c.CreateCommand();
cmd.CommandText = #" SELECT * FROM Authors ";
SqlDataReader reader = cmd.ExecuteReader();
dataGridView1.DataSource = reader;
dataGridView1.DataBind();
}
Error 1 'System.Windows.Forms.DataGridView' does not contain a definition for 'DataBind' and no extension method 'DataBind' accepting a first argument of type 'System.Windows.Forms.DataGridView' could be found.....
I am probably missing a "using directive" but which one? Multiple Google searches tell me how to bind a Yahoo RSS Feed to a gridview or provide various obscure details on "using directives".
Maybe I am using the SqlDataReader incorrectly. Should I be using SqlAdapter instead? What happened to all the good basic tutorials online for windows c# forms? A few months ago I found a couple great tutorials, but they seem to have lost their pageranking and I cannot find them anymore using basic google searches.
You're not missing a using directive; it's just that the WinForms DataGridView doesn't have a DataBind method. Just assigning DataSource is enough to get the binding to happen; you don't need to call a method as well.
However, I don't think you can assign a SqlDataReader as the DataSource. According to the DataSource property documentation in MSDN, the DataSource must be an IList, an IListSource, an IBindingList or an IBindingListView. You will probably instead need to load the data into a DataTable or DataSet (or an object data source populated using an object-relational mapper), and use that as the DataSource.
Try this instead:
using (SqlConnection conn = new SqlConnection("your connection string"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(#"SELECT * FROM Authors", conn))
{
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
adap.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
The DataGridView does not have a DataBind() method because it doesn't need one. Setting the DataSource property handles the binding for you. The using() blocks will automatically close and dispose of everything for you as well.
Note: you should replace "your connection string" with a valid connection string. I left yours out of my sample to avoid the horizontal scrollbars, and I'm not sure yours is valid anyway. You may get a runtime error when you run the code using your connection string. www.connectionstrings.com is a great resource for figuring out a valid connection string.
Update: instead of the nested using() blocks, you can also do it like this:
using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand(#" SELECT * FROM Authors", conn))
using (SqlDataAdapter adap = new SqlDataAdapter(cmd))
{
conn.Open();
DataTable dt = new DataTable();
adap.Fill(dt);
dataGridView1.DataSource = dt;
}
I prefer the nested style, but it's "half of one, six dozen of the other" to me. Typically, I would encapsulate code like this into a class (called "DataGetter" or whatever) with a static method like:
public static DataTable GetData(string query)
{
// do all the connecting and adapting and filling and so forth
}
so that the code in your button click would be as simple as:
dataGridView1.DataSource = DataGetter.GetData("SELECT * FROM AUTHORS");
However, I would not do this in any performance-critical section of my code, since you sometimes want to keep a SqlCommand object (and its SqlParameter collection) around between calls. You do not need to keep SqlConnection objects around between calls, thanks to connection pooling (in fact, you don't want to keep them around under any circumstances).

Categories