I am trying to search the database and set the results in textboxes. I am
getting error, which says "invalid cast exception". I need your guide please.
private void btn_search_Click(object sender, EventArgs e)
{
con.Open();
string STR="select * from TICKETSALES where REFERENCE="+txtSearch.Text;
cmd = new SqlCommand(STR,con );
dr = cmd.ExecuteReader();
if(dr.Read())
{
txtTrans.Text = dr.GetInt32("TRANSACTIONNUMBER").ToString();
txtPax.Text = dr.GetString("PASSENGERNAME");
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
Modify your select statement to get required column details.
While assigning values to test box, use column index to get value from dr
Convert value to string assign it to respective textbox
Here is sample implementation
con.Open();
//Use of camelCasing. transactionNumber instead of TRANSACTIONNUMBER
string STR="select transactionNumber,passengerNumber from TICKETSALES where REFERENCE=#search";
cmd = new SqlCommand(STR,con );
cmd.Parameters.Add("#search", txtSearch.Text);
dr = cmd.ExecuteReader();
if(dr.Read())
{
txtTrans.Text = Convert.ToString(dr[0]);
txtPax.Text = Convert.ToString(dr[1]);
}
Few tips for best coding practices (Credits: #tsahi-asher)
Don't pass values inside query, use parameters in query and use Paramere.Add() function to replace parameter with its value
Don't put your sql statements in presentation layer. Have some dedicated layer of SQL.
Don't use select *, use specific column name.
Don't use all-caps for identifier names, use camelCase.
How about something like this:
Note the sql injection protection by paramtising the sql query.
private void btn_search_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "select top 1 TRANSACTIONNUMBER, PASSENGERNAME from ticketsales where reference=#ref";
using (SqlDataAdapter adap = new SqlDataAdapter(query, con))
{
con.Open();
DataTable dt = new DataTable();
adap.SelectCommand.Parameters.AddWithValue("#ref", txtSearch.Text.Trim());
adap.Fill(dt);
if (dt.Rows.Count > 0)
{
txtTrans.Text = dt.Rows[0]["TRANSACTIONNUMBER"].ToString().Trim();
txtPax.Text = dt.Rows[0]["PASSENGERNAME"].ToString().Trim();
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
}
}
There are few issue already mentioned in comments and posts. I will chip in my remarks - you don't dispose of unmanaged resources, one answer covers that, but it violates your code. So here is alternative solution:
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//some methods, fields
private void btn_search_Click(object sender, EventArgs e)
{
con.Open();
// as it has benn already said, you have to prevent yourself from SQL injection!
cmd = (new SqlCommand("select * from TICKETSALES where REFERENCE=#ref", con)).Parameters.AddWithValue("#res", txtSearch.Text.Trim());
dr = cmd.ExecuteReader();
if (dr.Read())
{
txtTrans.Text = dr.GetInt32("TRANSACTIONNUMBER").ToString();
txtPax.Text = dr.GetString("PASSENGERNAME");
}
else
{
MessageBox.Show("Ticket Number not Found");
}
}
// it looks like you have unamanaged resources held by fields in your form,
// so to release them you have to call their Dispose() method!
// normally you should use using keyword if they were used locally in a method, as other answer states
public void Dispose()
{
base.Dispose();
if (con != null) con.Dispose();
if (cmd != null) cmd.Dispose();
if (dr != null) dr.Dispose();
}
Related
I have a Textbox with which I want to be able to Search and Insert data into Table. Insert works fine with one exception: When I try to Insert data that isn't already in DB(it's searching while I'm typing) it gives me:
"Exception User-Unhandled System.NullReferenceException: 'Object
reference not set to an instance of an object.'
System.Windows.Forms.DataGridView.CurrentRow.get returned null.
I think I'm missing something in the Search code.
//UPDATE: All of the code.// This is my Insert and Search code:
namespace UDDKT
{
public partial class FrmGlavna : Form
{
DataSet ds = new DataSet();
SqlDataAdapter DaDavaoci = new SqlDataAdapter();
SqlDataAdapter DaAkcije = new SqlDataAdapter();
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
public FrmGlavna()
{
InitializeComponent();
}
//Popunjava DataGridViews sa podacima iz baze
private void FrmGlavna_Load(object sender, EventArgs e)
{
SqlCommand SlctDavaoci = new SqlCommand("SELECT * FROM Davaoci ORDER BY DavaocID DESC", cs);
DaDavaoci.SelectCommand = SlctDavaoci;
DaDavaoci.Fill(ds, "TblDavaoci");
SqlCommand SlctAkcije = new SqlCommand("SELECT * FROM AkcijaDDK", cs);
DaAkcije.SelectCommand = SlctAkcije;
DaAkcije.Fill(ds, "TblAkcije");
DgDavaoci.DataSource = ds.Tables["TblDavaoci"];
}
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
//Osvježava DataGridView nakon unosa/izmjene/brisanja podataka u bazu
private void RefreshTable()
{
SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True");
String query = "SELECT * FROM Davaoci ORDER BY DavaocID DESC";
SqlCommand cmd = new SqlCommand(query, cs);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DgDavaoci.DataSource = dt;
}
//Čisti TextBox nakon upisa/izmjene/brisanja podataka u bazu
public void ClearTxtBx()
{
TxtIme.Clear();
TxtPrezime.Clear();
TxtTezina.Clear();
TxtAdresa.Clear();
TxtBrojTel.Clear();
TxtBrojLK.Clear();
}
//Upis podataka u Tabelu Davaoci
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UDDKT.mdf;Integrated Security=True"))
using (SqlCommand command = new SqlCommand(query, cs))
{
command.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
command.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
command.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
command.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = TxtDatumRodjenja.Text;
command.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
command.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
command.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
command.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
command.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
command.ExecuteNonQuery();
cs.Close();
RefreshTable();
ClearTxtBx();
}
}
//Pretraga postojećih Davalaca
private void TxtIme_TextChanged(object sender, EventArgs e)
{
(DgDavaoci.DataSource as DataTable).DefaultView.RowFilter = string.Format("Ime LIKE '{0}%'", TxtIme.Text);
}
}
}
}
Here is the MockUp of the Form before I begin to type/search/insert Data that isn't already in the Table (First Textbox*).
And after I start typing Name(Име) that starts with an "A" (name that isn't already in the Table).
I want to Search DB for that Column, but if there aren't any existing names, I want to be able to continue typing (without interuption) so that I can Insert new data into table.
DgDavaoci.CurrentRow in your DgDavaoci_SelectionChanged method is null, so attempting to access DgDavaoci.CurrentRow.Cells["DavaocID"] throws the NullReferenceException. The reason, best I can tell, is as follows:
You begin to type a value into your text box, a value that happens not to be found in the data set. As you type, you cause the TxtIme_TextChanged method to execute. It filters according to your search, and since the value is not found, it filters out every row in the set. Here's the important part: whenever the data set is filtered, it has the possibility of causing DgDavaoci_SelectionChanged to execute. Since the selection changed from the first row to no row at all (since there are no filtered rows to display), this method does execute. Now, when the method attempts to access the current row, there is no current row, and so we get a null here. Attempting to access a field of null throws the exception you're getting.
How can you fix this behavior? A simple null-check in DgDavaoci_SelectionChanged should do the trick. It looks to me like you can simply return from that method if(DgDavaoci.CurrentRow == null), or you can code in additional behavior. Just perform a check so that you don't reference the null object.
Probably the filter inside TxtIme_TextChanged is causing the DataGridView's SelectionChanged event to fire and the code is entering DgDavaoci_SelectionChanged. The exception indicates that DgDavaoci.CurrentRow is null, so you'll need to handle the case where DgDavaoci.CurrentRow is null in DgDavaoci_SelectionChanged.
A simple way to deal with this would be to just check DgDavaoci.CurrentRow is null and return from the function if that evaluates to true.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
It looks like you might have a second DataGridView (DgAkcije) that is designed to show the details of the currently selected row in DgDavaoci. So, another approach might be to just clear DgAkcije if DgDavaoci.CurrentRow is null.
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow is null)
{
DgAkcije.DataSource = null; //I'm not 100% sure this will work, I haven't tested it.
return;
}
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" +
DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
Ultimately, however, you'll have to decide what you want to happen when DgDavaoci_SelectionChanged is called but DgDavaoci.CurrentRow is null.
Solution if anyone else is interested:
//Povezuje DataGridViews Davaoca i Akcija
private void DgDavaoci_SelectionChanged(object sender, EventArgs e)
{
if (DgDavaoci.CurrentRow != null)
{
ds.Tables["TblAkcije"].DefaultView.RowFilter = "DavaocID =" + DgDavaoci.CurrentRow.Cells["DavaocID"].Value;
DgAkcije.DataSource = ds.Tables["TblAkcije"];
}
}
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;
}
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
I'm using SQL Server 2008 as my database in asp.net. And I'm passing the table name while at the time of clicking the <a> tag to web form. So how can I achieve this thing that when I click any link it change its sql query according to the value it receive?
For example:
<li class="last">
Item 1.1
</li>
Here cat contains the table name and sub contains the condition name.
And at the other side I'm doing:
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from Architect where subcategory3='" + s1 + "'",con);
da.Fill(ds,"tab");
dt = ds.Tables["tab"];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
So I just want that insted of giving table name Architect I just want to pass s - how can I do that?
I would suggest that you think of other solution for this because what you are currently doing will lead to a very simple SQL Injection and your database will be at a great risk. I suggest that you have an enum of all tables and pass the id of the table in the query string instead of the table name and also you should make sure that the condition string is valid from any sql injection before making the string concatination
Your design isn't really optimal; is it possible to consider storing all data in a central table linked to both Category and SubCategory?
There are several weaknesses; any string concatenation of sql leaves you open to SqlInjection attacks. Even if you are choosing values from drop down lists, for example, it is still possible for client side script to modify the values in your combo boxes, or for an attacker to simply post data to your server side event handler.
In addition, having to source data from several tables means that you may have to deal with different schemas in your results; if you expect this (i.e. some tables will have more columns than others) then you can handle it appropriately.
Your query would then become something similar to:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Table WHERE Category = #Category AND SubCategory = #SubCategory";
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#Category", Value = s });
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
If you are stuck with your original model, then you may want to whitelist the table names so you can stick with parameterised queries:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
if(String.IsNullOrEmpty(s) || String.IsNullOrEmpty(s1)) { return; } //Improve Validation and error reporting
using(SqlConnection conn = new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag"))
{
using(SqlCommand command = new SqlCommand(conn))
{
command.CommandType = CommandType.Text;
switch(s)
{
case "Architect":
command.CommandText = "SELECT * FROM Architect WHERE SubCategory = #SubCategory";
break;
case "SomethingElse":
command.CommandText = "SELECT * FROM SomethingElse WHERE SubCategory = #SubCategory";
break;
default:
return; //Again, improve error handling
}
command.Parameters.Add(new SqlParameter() { Type = SqlDbType.String, Name = "#SubCategory", Value = s1 });
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable("MyData");
data.Load(reader);
DataGrid1.DataSource = data;
DataGrid1.DataBind();
}
}
}
}
}
One comment I would make though, is that even if you implement either of the examples above, you still have a big problem; your data access code, business logic, and presentation code are all now munged into the code behind for this page. You will have to repeat this everywhere you need it leading to plenty of duplication, which is especially a problem when you need to fix bugs.
Instead, you might consider creating classes or using an ORM to handle all of this work for you, so you instead request a list of Architect objects, or a list of SomethingElse from a class or component, thus leaving the aspx to deal with the presentation. There is also a discussion here about why you might not want to use an ORM.
If you follow this route, your code might then become something like:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
//Still do validation on s and s1
ObjectFactory of = new ObjjectFactory();
DataGrid1.DataSource = ObjectFactory.GetObjects(s, s1);
DataGrid1.DataBind();
}
}
Effectively, it is now someone else's job to worry about how to get the objects, and to collect them, vastly reducing the code you have in your code behind. Plus you can easily reuse that across a wide variety of interfaces!
da = new SqlDataAdapter("select * from " + s + " where subcategory3='" + s1 + "'",con);
Like this ?
SqlConnection con=new SqlConnection("Data Source=ANURAG-PC;Initial Catalog=dbPortal;Persist Security Info=True;User ID=sa;Password=anurag");
SqlDataAdapter da;
DataSet ds=new DataSet();
static DataTable dt=new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
string s = Request.QueryString["cat"];
string s1 = Request.QueryString["sub"];
da = new SqlDataAdapter("select * from '"+s+"' where subcategory3='" + s1 + "'",con);
da.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
I'm not really used to C# sharp but have used VB.NET before.
I'm needing to set the value of text fields, dropdowns etc from data from a query. To enter the data I have been using a class Computer with the method saveComputer() that takes values from user controls. Now I want an edit page that uses the id from url & uses getComputer(id) from Computer class and returns the values to be set to the user controls. I'm unsure about using this method to set the control values.
Edit.aspx.cs
protected void btnSave_Click(object sender, EventArgs e)
{
int id = 3; //will be replaced to GET value
Computer comp = new Computer();
//comp.updateComputer(ref id);
}
My Computer class
public getComputer(ref int id)
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection(
"Server=JURA;Database=ReadyForSeven;User id=;Password="))
{
String sql = "SELECT * FROM computers WHERE id=#id";
//replace contatenation of variable with parameter name
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql.ToString();
cmd.CommandType = CommandType.Text;
//Define SqlParameter object and assign value to the parameter
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = id;
try
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(data);
// return data here
}
}
catch (SqlException ex)
{
//send user to error page and log message
}
}
}
So what I'm wanting to achieve is using the getcomputer method of Computer to set the values of the controls on Edit.aspx
Can anyone help me out?
You'll need to modify your getComputer method to return a DataSet like:
public DataSet getComputer(int id) {
Once that's done we can call it and populate the form controls on the page load with something like:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
int id = 3; // get from querystring
DataSet ds = getComputer(id);
DataRow dr = ds.Tables[0].Rows[0]; // get the first row returned
// populate form controls
txtFirstName.Text = dr["FirstName"].ToString();
ddlState.SelectedValue = dr["State"].ToString();
}
}
Below is an updated version of getComputer that will always return a value and is a little tighter:
public DataSet getComputer(int id) // you don't need to pass int by ref unless you're planning on changing it inside this method
{
DataSet data = new DataSet();
using (SqlConnection conn = new SqlConnection("Server=JURA;Database=ReadyForSeven;User id=;Password=")) {
using (SqlCommand cmd = new SqlCommand("SELECT * FROM computers WHERE id = #id", conn)) {
cmd.Parameters.AddWithValue("id", id);
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
da.Fill(data);
return data;
}
}
}
}
I had to remove the try/catch blog to ensure the method always returned a value. If you absolutely need the try/catch block you'll need to return an empty DataSet at the end of the method to get to compile correctly.