I have created comboBox and filled with one column, after I choose item from the combobox I would like to show other column in the textboxs so I wrote code to make it happen but what if I want to choose column from another table I mean I would like to show couple of columns from two different table in the textbox when I hit the combobox
Here is my code:
private void comboLname_SelectedIndexChanged(object sender, EventArgs e)
{
string conn = "Data Source=srv-db-02;Initial Catalog=rmsmasterdbtest;Persist Security Info=True;User ID=test;Password=*******";
string Query = "select * from rmsmasterdbtest.dbo.customer where LastName= '" + comboLname.Text + "' ;";
SqlConnection Myconn = new SqlConnection(conn);
SqlCommand cmdDataBase = new SqlCommand(Query, Myconn);
SqlDataReader Reader;
try
{
Myconn.Open();
Reader = cmdDataBase.ExecuteReader();
while (Reader.Read())
{
string ID = Reader.GetInt32(Reader.GetOrdinal("ID")).ToString();
string AccountNuber = Reader.GetString(Reader.GetOrdinal("AccountNumber"));
//string Time = Reader.GetString(Reader.GetOrdinal("Time"));
// string Deposit = Reader.GetString(Reader.GetOrdinal("Deposit"));
string sstatus = Reader.GetString(Reader.GetOrdinal("status"));
string slastname = Reader.GetString(Reader.GetOrdinal("lastname"));
txtid.Text = ID;
txtacnum.Text = AccountNuber;
//txttime.Text = Time;
//txtdeposit.Text = Deposit;
txtstatus.Text = sstatus;
txtlname.Text = slastname;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
Myconn.Close();
}
}
Related
Trying to update the first name of the student there is a textbox "FirstNameTextbox" information was loaded to it from the DB, when I change the information in the textbox and try to write the changes it read only the original data.So if it loaded "Craig" as the first name from the DB, i would edit and put "Chris" in the textbox, what happens is that Craig is written to the DB and not "Chris"
int stuID = getSqlStuID(IDNUMLabel.Text);
SqlConnection conn = new SqlConnection(GetConnectionString());
string sqlUpdateStudent = "Update tblStudent set fname = #fname where stuID = #stuID";
SqlCommand cmd = new SqlCommand(sqlUpdateStudent, conn);
conn.Open();
cmd.Parameters.AddWithValue("#stuID", stuID);
cmd.Parameters.AddWithValue("#fname", FirstNameTextbox.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Text = "Success";
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
IDNUMLabel.Text = Session["User"].ToString();
getStuData(Session["User"].ToString());
}
else
{
Response.Redirect("../Login/Login.aspx");
}
}
private void getStuData(string id)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "Select fname, sname From tblStudent Where idnumber = '" + id + "' ";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
SqlDataReader selectedRecord = cmd.ExecuteReader();
cmd.CommandType = CommandType.Text;
while (selectedRecord.Read())
{
FirstNameTextbox.Text = selectedRecord["fname"].ToString();
LastNameTextbox.Text = selectedRecord["sname"].ToString();
}
selectedRecord.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
//id = 0;
//string msg = "Error reading Student ID";
//msg += ex.Message;
//throw new Exception(msg);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
At what point do you make the actual update? After a button was pressed, after the value was entered on the textbox...? You're missing the method in which the code that handles the update is placed...
Maybe this could help: How to display data from database into textbox, and update it
They're must be a minor error somewhere in my code that im not seeing as to why on my web page , the gridview only outputs one row when i know the query works/
Both rows from management studio
Only one row in ASP page
heres my c#
string AdminID = Request.QueryString["ID"];
string AdminsCurrentLocation = Request.QueryString["Location"];
//retrieve admin location
try
{
string connectionString = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
//
// Create new SqlConnection object.
//
using (SqlConnection connection5 = new SqlConnection(connectionString))
{
connection5.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM [DB_A05369_WATERQ].[dbo].[S_CONTROL] WHERE LOGIN = '" + AdminID + "'", connection5))
{
//
// Invoke ExecuteReader method.
//
using (SqlDataReader reader2 = command.ExecuteReader())
{
reader2.Read();
TempLocationIdbox.Text = (reader2["ALL_LOCATION_ACCESS"].ToString());
}
}
connection5.Close();
}
}
catch (Exception ex) { }
if(TempLocationIdbox.Text == "Y")
{
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM " +
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM " +
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND ACT.LOCATION_ID = LOC.ROW_ID AND ACT.MEMBER_ID = MEM.ROW_ID", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
else if (TempLocationIdbox.Text == "N")
{
string strSQLconnection1 = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection1 = new SqlConnection(strSQLconnection1);
SqlCommand sqlCommand1 = new SqlCommand("SELECT * FROM S_LOCATION WHERE NAME = '" + AdminsCurrentLocation + "'", sqlConnection1);
sqlConnection1.Open();
string locationrowID = "";
SqlDataReader reader12 = sqlCommand1.ExecuteReader();
if (reader12.HasRows)
{
reader12.Read();
locationrowID = reader12["ROW_ID"].ToString();
}
sqlConnection1.Close();
string strSQLconnection = "Data Source=SQL5027.HostBuddy.com;Initial Catalog=DB_A05369_WATERQ;User Id=DB_A05369_WATERQ_admin;Password=waterqws1";
SqlConnection sqlConnection = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand = new SqlCommand("SELECT DISTINCT ACT.ROW_ID , ACT.CREATED , MEM.FIRST_NAME , MEM.LAST_NAME , LOC.NAME , CAT.NAME , SER.NAME , EMP.FIRST_NAME , EMP.LAST_NAME , SER.DURATION , ACT.CASH , COS.NAME , ACT.COMMENTS FROM "+
"S_ACTIVITY ACT, S_LOCATION LOC, S_CATEGORY CAT, S_EMPLOYEE EMP, S_SERVICE SER, S_COST_CODE COS, S_MEMBER MEM "+
"WHERE ACT.EMPLOYEE_ID = EMP.ROW_ID AND ACT.SERVICE_ID = SER.ROW_ID AND ACT.CATEGORY_ID = CAT.ROW_ID AND ACT.COST_CODE_ID = COS.ROW_ID AND "+
"ACT.LOCATION_ID = '"+ locationrowID + "' AND ACT.MEMBER_ID = MEM.ROW_ID AND LOC.NAME = '"+ AdminsCurrentLocation + "'", sqlConnection);
sqlConnection.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
//collect rowID
string retrievedROWID = "";
if (reader.HasRows)
{
reader.Read();
string temp1 = reader["ROW_ID"].ToString();
retrievedROWID = temp1;
GridView1.DataSource = reader;
GridView1.DataBind();
}
sqlConnection.Close();
}
What stumps me is that my other query is working fine for the case where TempLocationIdbox.Text == "Y"...
Thanks , any help would be much appreciated.
Instead of using if (reader.HasRows) you need to use while (reader.Read()).Also created some kind of collection for example List<T> and populate it with results inside the while loop.Then outside the loop set the DataSource of the GridView control to point to List<T>.Here's a complete example:
public class Activity
{
public int RowID { get; set; }
public DateTime Created { get; set; }
public string FirstName { get; set; }
}
public partial class UsingSqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.GetData();
}
}
private void GetData()
{
string cs = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
var activities = new List<Activity>();
using (var con = new SqlConnection(cs))
{
using(var cmd = new SqlCommand("SELECT ACT.ROW_ID,ACT.CREATED,ACT.FIRST_NAME FROM [dbo].[S_ACTIVITY] ACT", con))
{
cmd.CommandType = System.Data.CommandType.Text;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var activity = new Activity();
activity.RowID = Convert.ToInt32(reader["ROW_ID"]);
activity.Created = DateTime.Parse(reader["CREATED"].ToString());
activity.FirstName = Convert.ToString(reader["FIRST_NAME"]);
activities.Add(activity);
}
}
}
}
GridView1.DataSource = activities;
GridView1.DataBind();
}
}
Output:
A better solution would be to put your in-line query in a stored proc and execute the stored proc.
You could also bring it in a dataset and bind the gridview with that. but that is completely your choice.
In-line queries are very error prone and results could be unpredictable hence refrain using that.
I'm currently making a voting app on C# Windows Form.
So I made a SQL query to count how many people voted for a specific candidate that will be displayed on textBox4
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How to display the results of the above SQL query to textBox4?
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using (sqlcon)
{
SqlCommand com = new SqlCommand(cek, sqlcon);
com.Parameters.Add("idcan", SqlDbType.VarChar, 5).Value = score;
}
try
{
sqlcon.Open();
textBox4.Text=Convert.ToString(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can actually do this code:
private void button1_Click(object sender, EventArgs e)
{
string idcan = textBox3.Text;
string score = textBox4.Text;
Datatable dt = new DataTable();
Connection con = new Connection();
SqlConnection sqlcon = con.Sambung();
SqlCommand com ;
sqlcon.Open();
string cek = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
using(sqlcon)
{
using(com = new SqlCommand(cek, sqlcon))
{
sqlcon.Open();
com.Parameter.Add("#idcan",score );
SqlDataAdapter da = new SqlDataAdapter(com);
da.File(dt);
if(dt.Rows.Count > 0)
{
textBox4.Text = dt.Rows[0]["Score"].ToString();
}
}
}
}
Since your SELECT statement returns one row with one column, you can use ExecuteScalar to get it.
textBox4.Text = com.ExecuteScalar().ToString();
And your code needs a little bit refactoring like;
using(SqlConnection sqlcon = con.Sambung())
using(SqlCommand com = sqlcon.CreateCommand())
{
com.CommandText = "select count (ID_Candidate) as Score from DataVote where ID_Candidate = #idcan";
com.Parameters.Add("#idcan", SqlDbType.VarChar, 5).Value = score;
sqlcon.Open();
textBox4.Text = com.ExecuteScalar().ToString();
}
By the way, I strongly suspect your ID_Candidate column should be some numeric type instead of VarChar based on it's name.
Expand your question: If your query return as a table (many columns, many rows), you can use this code below. Similar for case return single value.
//Create class to store result value
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
// In query code
ClassName[] allRecords = null;
SqlCommand command = ...; // your code
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName {Col1 = reader.GetString(0), Col2 = reader.GetInt32(1)});
allRecords = list.ToArray();
}
I have filled the drop down menu with names from the my UserData database. I am currently trying to select an users name to make their user details appear in the textboxes, however when I try to select an option from the dropdown menu, the first option always appears in the textboxes I was wondering if anybody could see a problem in my code?
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = DropDownList1.SelectedItem.Value;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval"+ ex.StackTrace);
}
finally
{
conn.Close();
}
}
Try altering your code slightly like this and then you will find it easier to debug. Check what value you're getting for the selected value (is it what you expect) and also what the content of the actual exception is that you're getting.
This should help you to work out what's going on.
protected void BtnSelect_Click(object sender, EventArgs e)
{
SqlDataReader reader;
String connString = ConfigurationManager
.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm1 = new SqlCommand(
"SELECT FirstName, LastName, Email FROM UserData " +
"WHERE TeacherID = #TeacherID", conn);
var selectedValue = DropDownList1.SelectedItem.Value;
var selected = int.Parse(selectedValue);
comm1.Parameters.Add("#TeacherID", System.Data.SqlDbType.Int);
comm1.Parameters["#TeacherID"].Value = selected;
try
{
conn.Open();
reader = comm1.ExecuteReader();
if (reader.Read())
{
txtFirstName.Text = reader["FirstName"].ToString();
txtLastName.Text = reader["LastName"].ToString();
txtEmail.Text = reader["Email"].ToString();
}
reader.Close();
}
catch(Exception ex)
{
dbErrorLabel.Text = ("Error in retrieval " + ex.StackTrace );
}
finally
{
conn.Close();
}
}
I have this basic WinForms application user interface:
And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName ProduktTable ("
+ dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
+ dataGridView1.Rows[i].Cells["Antal"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:
What's wrong with the procedure ?.
Thanks in advance
The format for an insert name doesn't require the words tableName. It wants the actual table name.
INSERT INTO tableName ProduktTable
should be
INSERT INTO ProduktTable
assuming Produ**K**tTable isn't a typo.