Disclaimer - yes I googled, clearly I didn't find a solution.
Webform, ASP.NET, SQL, no sqldatasource - all codebehind.
Ok, looks like I was misunderstanding what was going wrong in my application.
Using .SelectedValue does get the correct value of the drop down item - but only in my Insert() method, .SelectedValue returns empty in my UpdateMethod.
Insert()
using (con = new SqlConnection(conString))
{
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Building(Building_Code, Building_Name, Company_ID, Active) VALUES(#BuildingCode, #BuildingName, #CompanyID, #Active)", con);
cmd.Parameters.AddWithValue("#BuildingCode", txtBuildingCode.Text);
cmd.Parameters.AddWithValue("#BuildingName", txtBuildingName.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
cmd.Parameters.AddWithValue("#Active", chkBuildingActive.Checked);
cmd.ExecuteNonQuery();
}
Update()
using (con = new SqlConnection(conString))
{
try
{
if (ddlCompanyCode.SelectedIndex >= 1)
{
con.Open();
cmd = new SqlCommand("UPDATE Building SET Building_Name = #BuildingName, Company_ID = #CompanyID, Active = #Active WHERE Building_ID = #BuildingID", con);
cmd.Parameters.AddWithValue("#BuildingID", selectedRecordID);
cmd.Parameters.AddWithValue("#BuildingName", txtBuildingName.Text);
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
cmd.Parameters.AddWithValue("#Active", chkBuildingActive.Checked);
cmd.ExecuteNonQuery();
}
}
catch (SqlException sqlExc)
{
MessageBox.Show(sqlExc.Message);
}
}
BindForm()
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtBuildingCode.Text = reader["Building_Code"].ToString();
txtBuildingName.Text = reader["Building_Name"].ToString();
ddlCompanyCode.SelectedItem.Text = reader["Company_Code"].ToString();
chkBuildingActive.Checked = reader.GetBoolean(reader.GetOrdinal("Active"));
}
}
catch (SqlException sqlExc)
{
MessageBox.Show(sqlExc.Message);
}
What would cause this issue?
Instead using ddlCompanyCode.DataValueField use SelectedValue property
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedValue);
You can as well use SelectedItem.Value like
cmd.Parameters.AddWithValue("#CompanyID", ddlCompanyCode.SelectedItem.Value);
Woo! I got a solution from a friend.
Create a local variable for the company code value
string strCompany = "";
Read the contents of the datareader to the variable
txtBuildingCode.Text = reader["Building_Code"].ToString();
txtBuildingName.Text = reader["Building_Name"].ToString();
strCompany = reader["Company_Code"].ToString();
Then set the SelectedIndex of the drop down to the item index by
ddlCompanyCode.SelectedIndex = ddlCompanyCode.Items.IndexOf(ddlCompanyCode.Items.FindByText(strCompany));
Thanks for everyones help!
Related
I want to shift some variables by one. I searched for the command for it but I couldn't find. If anybody knows it please help me.
Here is the code:
private int shiftNumbers(int number)
{
int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
try
{
con.Open();
cmd = new MySqlCommand(stm, con);
cmd.Parameters.AddWithValue("#number", number);
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
try
{
rdr = cmd.ExecuteReader();
while(rdr.Read()) {
newNumber = rdr.GetInt32(1);
cmd.Parameters.AddWithValue("#newNumber ", (newNumber-1));
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
con.Close();
return 1;
}
I know this code useless but I show it for you to get the logic that I want to do.
I think your approach is wrong.
First, you read from the database, using a select statement;
Then you go over that result, your rdr.Read();
Then you create a new command, updating the original record;
Move forward in your reader (rdr) and repeat from 2 until you are done.
What you are doing now is impossible. You can't get a result set from an update, just a count affected.
Or, if you can, let your update statement do the calculation (it seems it is only subtracting one from the original number, so why not do that in SQL?):
string stm = "UPDATE devices SET number = number - 1 WHERE number>#number";
Yes, your code is really useless. In your update statement you are passing a parameter #newNumber bu not providing it. Closing the connection in catch block.
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
First decide from where you are going to get the #newNumber value and then add that as parameter and use ExecuteNonQuery() method.
If you want pass the other parameter as well in your method and use it like
private int shiftNumbers(int number, int newNumber)
{
//int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
using(SqlConnection con = new SqlConnection(connectionString))
{
cmd = new MySqlCommand(stm, con);
SqlParameter paramNumber = new SqlParameter("#number", SqlDbType.Int);
paramNumber.Value = number;
SqlParameter paramNewNumber = new SqlParameter("#newNumber", SqlDbType.Int);
paramNewNumber.Value = newNumber;
cmd.Parameters.Add(paramNumber);
cmd.Parameters.Add(paramNewNumber);
con.Open();
cmd.ExecuteNonQuery();
}
//Rest of your code logic if any
}
I have a MS-Access table in my database called "RichtingEnJaar".
This table has 2 columns: the "ID" and "Naam".
I need to get the whole column "Naam" to be in an array in C#.
I tried a lot already but can't seem to find the correct answer.
Can any of you help me out real quick?
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
connect.Open();
OleDbCommand cmdKlassen = new OleDbCommand("SELECT Naam FROM RichtingEnJaar WHERE ID = 1", connect);
if (connect.State == ConnectionState.Open)
{
try
{
OleDbDataReader KlasReader = null;
KlasReader = cmdKlassen.ExecuteReader();
while (KlasReader.Read())
{
Klas[0].Naam = KlasReader["Naam"].ToString();
}
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection failed");
}
Tried a new one:
string connStringKlas = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
DataTable resultsKlas = new DataTable();
using (OleDbConnection connKlas = new OleDbConnection(connStringKlas))
{
OleDbCommand cmdKlas = new OleDbCommand("SELECT Naam FROM RichtingEnJaar", connKlas);
connKlas.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmdKlas);
adapter.Fill(resultsKlas);
for (int i = 0; i <= resultsKlas.Rows.Count - 1; i++)
{
Klas[i].Naam = resultsKlas.Rows[i].ToString();
}
connKlas.Close();
}
MessageBox.Show(Klas[0].Naam.ToString());
Got an error on line Klas[i].Naam = resultsKlas.Rows[i].ToString(); saying 'System.NullReferenceException'.
It is not quite clear what Klas is, but supposing it is some array.
It looks like Klas[0].Naam = KlasReader["Naam"].ToString(); is problem source. You're putting all results from query into the same variable.
It should be some list or another collection you're adding your query results to, not a single Klas[0].Naam variable.
For example (skipping irrelevant parts of your code)
var list = new List<KlasStruct>();
while (KlasReader.Read())
{
var k = new KlasStruct();
k.Naam = KlasReader["Naam"].ToString()
list.Add(k);
}
And later (if you really need array, not list) you can transform list to array using List.ToArray() method.
Like this:
Klas = list.ToArray();
Since you may not know how many records there are in your database, you can use a list to fill from the database, and convert this list to an array:
var klasList = new List<KlasStruct>();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\Project Officieel\Project_MagnusCurriculum\Project_MagnusCurriculum\Project.accdb";
connect.Open();
OleDbCommand cmdKlassen = new OleDbCommand("SELECT Naam FROM RichtingEnJaar WHERE ID = 1", connect);
if (connect.State == ConnectionState.Open)
{
try
{
OleDbDataReader KlasReader = null;
KlasReader = cmdKlassen.ExecuteReader();
while (KlasReader.Read())
{
klasList2.Add(new KlasStruct() { Naam = KlasReader["Naam"].ToString());
}
connect.Close();
Klas = klasList.ToArray();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("Connection failed");
}
So I have this code that is designed to delete a row in mySQL server database judging by what is selected in my list box. Here is the code I have to remove the rows:
private void remove_btn_Click(object sender, EventArgs e)
{
try
{
if (Calls_lsb.SelectedItem == null)
MessageBox.Show("Please select an item for deletion.");
}
else
{
int i = Calls_lsb.SelectedIndex;
if (i > 0)
{
SqlConnection connection = new SqlConnection(//My Connection String);
string sqlStatement1 = "DELETE FROM Records WHERE CallID = #Id";
string sqlStatement2 = "DELETE FROM Calls WHERE CallID = #Id";
connection.Open();
SqlCommand cmd1 = new SqlCommand(sqlStatement1, connection);
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd1.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand(sqlStatement2, connection);
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
cmd2.ExecuteNonQuery();
connection.Close();
Calls_lsb.Items.Remove(Calls_lsb.Items[i]);
}
else
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I get no exceptions and I have similar code that adds records that works fine. I tried stepping into the code but it all seemed fine. It simply just does not delete the row from the database. It removes the correct item from the list, just not the database.
If anyone could shine some light on this situation that would be great, thanks!
Edit : Ok, I seem to have fixed the problem. I just removed the whole i = selected index stuff and replace the 'Calls_lsb.Items[i]' with '(Calls_lsb.SelectedIndex + 1)'. I don't really understand why I was getting an exception when I tried to add 1 to i as this is basically doing the same thing.
Replace your below line code.
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
//with
cmd1.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
and
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i]);
// with
cmd2.Parameters.AddWithValue("#Id", Calls_lsb.Items[i].Value);
While I am running the code below, the compiler is giving me the error: "object reference not set to an instance of an object". Please can you tell what mistakes I have made in this code.
public void text()
{
cn1.Open();
string s;
//error came here
s = "select Request_Type from dbo.component where Material_Code='" +
Mcodeddl.SelectedItem.Text + "' ";
//end
SqlCommand cd1 = new SqlCommand(s, cn1);
SqlDataReader rd;
try
{
rd = cd1.ExecuteReader();
while (rd.Read())
{
TextBox4.Text = rd["Request_Type"].ToString().Trim();
}
rd.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
finally
{
cd1.Dispose();
cn1.Close();
}
}
Just a hunch, but either Mcodeddl or Mcodeddl.SelectedItem is null.
There is probably no selected item in the (assuming) dropdown control.
Add a null check on the Mcodeddl.SelectedItem object before the code with the error to prevent that from happening.
var code = Mcodeddl.SelectedItem.Text; // you may need to check Mcodeddl.SelectedItem != null here, if you not set default selected item
if (string.IsNullOrEmpty(code)) return; // return if code type empty, or show message. depending on your requirement
using (SqlConnection connection = new SqlConnection(connectionString)) // using statement will dispose connection automatically
{
connection.Open();
using (SqlCommand command = new SqlCommand("select Request_Type from dbo.component where Material_Code= #MaterialCode", connection))
{
command.Parameters.AddWithValue("#MaterialCode", code); // use parameters
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var request = reader["Request_Type"];
TextBox4.Text = request != DBNull.Value ? request.ToString().Trim() :string.Empty;// check null before ToString
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message);
}
I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result