Please take a look at the following code.
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand();
if (DropDownList3.SelectedItem.Text == "Economy")
{
seats = Convert.ToInt32(DropDownList1.SelectedItem.Text);
cmd.Connection = con;
con.Open();
cmd.CommandText = "select easeats from flight where fno='" + fn + "'";
int eds = Convert.ToInt32(cmd.ExecuteScalar());
if (eds > seats)
{
Panel2.Visible = true; //seats available
cl = DropDownList3.SelectedItem.Text;
seat = seats.ToString();
seats = eds;
}
else
{
Panel3.Visible = true; // seats not available
}
con.Close();
}
}
I am getting error in the line:int eds = Convert.ToInt32(cmd.ExecuteScalar());
And the error is
error in converting varchar value to datatype int
What is wrong with this code?
Firstly, NEVER construct your query like this. Use parameterized queries instead.
Secondly, the error message is quite clear - you're trying to convert to int some varchar column, that probably contains some literal characters as well and not only numbers...
Thirdly, prefer "using" statements over explicitly closing the connection. It's more safe that way.
try to replace:
int eds = Convert.ToInt32(cmd.ExecuteScalar());
with:
int eds = 0;
int.TryParse(cmd.ExecuteScalar(), out eds);
in this way if the Convert fails you have no issues and continue with eds = 0...
side note, your handling of exceptions and connection lifetime is very poor, think about replacing the whole block in this way:
protected void Button2_Click(object sender, EventArgs e)
{
using(var con = new SqlConnection(constring))
using(var cmd = con.CreateCommand())
{
if (DropDownList3.SelectedItem.Text == "Economy")
{
seats = Convert.ToInt32(DropDownList1.SelectedItem.Text);
con.Open();
cmd.CommandText = "select easeats from flight where fno='" + fn + "'";
int eds = 0;
object result = cmd.ExecuteScalar();
int.TryParse(result, out eds);
if (eds > seats)
{
Panel2.Visible = true; //seats available
cl = DropDownList3.SelectedItem.Text;
seat = seats.ToString();
seats = eds;
}
else
{
Panel3.Visible = true; // seats not available
}
}
}
}
of course, anyway, you should also consider to refactor the whole thing and separate clearly database and business logic from UI logic, in general you should never deal directly with connections and queries inside the UI and even less in a ButtonClick event handler.
Related
im creating e grades project on c#, and i cant normally connect to database. Writing https://i.stack.imgur.com/itJuX.png
Maybe you can help me ? Not working in login.cs. Last job then i do it it was working.
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dienynas.mdf;Integrated Security=True;"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
int id = 0;
bool pass = false;
while (sdr.Read())
{
if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)
{
pass = true;
id = (int)sdr[0];
break;
}
}
if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Your problem is in your if statement after the loop.
if (pass == false)
{
MessageBox.Show("Password for this user is incorrect");
id = (int)sdr[0];
pass = true;
}
In that if block you are accessing your SqlDataReader, which very possibly has exited the while loop after returning false upon reading indicating that there is no more data to be read. If there is no data, then you will get an error when attempting to read data that is not there.
I would think that one of the reasons you are exiting the while without ever having a match is that, unless both TextBox1 and TextBox2 contain a matching string you will never have a match. The following line is comparing those text box values to the exact same data value. Unless the text is identical between those text boxes then this statement will always be false.
if (sdr[0].ToString() == textBox1.Text && sdr[0].ToString() == textBox2.Text)
I am guessing that you intended something like this:
if (sdr[0].ToString() == textBox1.Text && sdr[1].ToString() == textBox2.Text)
Edit
With all of that being said, there is a lot of room for refactoring in this code. For one thing, generally performing database operations in a button handler can lead to unresponsive dialog windows and is something to be avoided. You are also using some other objects which are disposable and so you should be cleaning those up as well. I will rewrite the function a little to show you some of the cleanup, but I don't have time to go through splitting it into threads and it is outside the scope of your question.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader sdr = null;
try
{
var textBox1 = textBox1.Text;
var textBox2 = textBox2.Text;
conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dienynas.mdf;Integrated Security=True;");
conn.Open();
cmd = new SqlCommand("select * from users", conn);
sdr = cmd.ExecuteReader();
int id = -1;
while (sdr.Read())
{
var text0 = sdr[0].ToString();
var text1 = sdr[1].ToString();
// NOTE: You could add the string comparison type here as well
if (text0.Equals(textBox1) && text1.Equals(textBox2))
{
id = (int)sdr[0];
break;
}
}
if (id == -1)
{
MessageBox.Show("Password for this user is incorrect");
}
else
{
Form1 frm = new Form1(id);
Hide();
frm.Show();
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sdr?.Dispose();
cmd?.Dispose();
conn?.Dispose();
}
}
I'm trying to get data from the SQL Server database but the error state that
System.IndexOutOfRangeException: Index was outside the bounds of the array.
This is my table
TourDisplay
My code:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=....;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand cmd = new SqlCommand();
SqlDataReader dtr;
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select BicycleType from TourDisplay order by TDateTime asc";
dtr = cmd.ExecuteReader();
bool temp = false;
while (dtr.Read())
{
TBBicycleType.Text = dtr.GetString(0);
TBBicycleType2.Text = dtr.GetString(1);
temp = true;
}
}
As you can see, the code should be fine because I got 3 data inside the table but I'm having problem on GetString(1).
It appears that in your select statement, you are selecting ONE column, but in the reader, you're trying to select two.
EXAMPLE: SELECT Id, BicycleType FROM TourDisplay ORDER BY TDateTime
Please either add another column to your select statement, or remove the second selector from the reader:
TBBicycleType2.Text = dtr.GetString(1);
Edit per comment
It appears that you may be trying to set two different buttons, using the first two results from your query with this while reader loop. I'd tweak it a little as follows:
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT BicycleType FROM TourDisplay ORDER BY TDateTime";
dtr = cmd.ExecuteReader();
bool temp = false;
// Added this variable. name it anything you like.
bool isFirstItem = true;
while (dtr.Read())
{
// After the first loop iteration, isFirstItem will be set to false
if (isFirstItem)
{
TBBicycleType.Text = dtr.GetString(0);
isFirstItem = false;
}
// All consequent iterations of the loop will set the second
// item's 'Text' property. So if you have only two rows, it
// will be the second row. If you have 20 rows, it will be the 20th row.
else
TBBicycleType2.Text = dtr.GetString(0);
temp = true;
}
}
Although, if you're just setting two buttons using a while loop and from the database, I'd rethink your design a little?
Edit 2 per changes to the OP mentioning 3 total rows in the database
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT BicycleType FROM TourDisplay ORDER BY TDateTime";
dtr = cmd.ExecuteReader();
// Again, I'd rethink your design, but if you're just playing
// around this should be fine
int count = 0;
while (dtr.Read())
{
switch (count)
{
case 0:
TBBicycleType.Text = dtr.GetString(0);
break;
case 1:
TBBicycleType2.Text = dtr.GetString(0);
break;
// Add whatever you want to do with the third one here
// case 2:
// TBBicycleType3.Text = dtr.GetString(0);
// break;
}
count++;
}
}
The index is indeed out of bounds. Since you're trying to get the second column on dtr.getString(1). To fix, remove the dtr.getString(1).
In each iteration, dtr.GetString(0) gets the next row of BicycleType. So first iteration, TBBicycleType.Text = "Time Trial". Second iteration, TBBicycleType.Text = "MTB". and so on.
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=....;Integrated Security=True;Connect Timeout=30;User Instance=True;");
SqlCommand cmd = new SqlCommand();
SqlDataReader dtr;
protected void Page_Load(object sender, EventArgs e)
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "select BicycleType from TourDisplay order by TDateTime asc";
dtr = cmd.ExecuteReader();
bool temp = false;
while (dtr.Read())
{
TBBicycleType.Text = dtr.GetString(0);
temp = true;
}
}
I am attempting to change my code. I am in the process of learning while I code and many parts of my C#/ASP.Net application use LINQ to SQL and many parts use commands to directly access the sql database. I felt like I should standardize these, so I am changing over the LINQ to SQL code. I have a portion of the code that takes the finds one record based on a session variable and then populates the labels in my header with the sql query results. here is the code:
protected void Page_Load(object sender, EventArgs e)
{
var pinNum = MySession.Current.focusParcel;
if (pinNum != 0)
{
String sql = ConfigurationManager.ConnectionStrings["Recorder"].ConnectionString;
SqlConnection connection = new SqlConnection(sql);
connection.Open();
SqlCommand command = new SqlCommand("Select PARCEL, PIN_TXT, Owner, Address1, Address2, CSZ, ACRES, LEGAL, Active FROM[ParcelView] WHERE PARCEL = " + pinNum, connection);
SqlDataReader selectedParcel = command.ExecuteReader();
if (selectedParcel != null)
{
lblPIN_Num.Text = selectedParcel["PARCEL"].ToString();
lblPIN_TXT.Text = selectedParcel["PIN_TXT"].ToString();
lblDateTime.Text = DateTime.Now.ToString("MMMM dd, yyyy");
lblOwner.Text = selectedParcel["Owner"].ToString();
lblAddress1.Text = selectedParcel["Address1"].ToString();
lblAddress2.Text = selectedParcel["Address2"].ToString();
lblCSZ.Text = selectedParcel["CSZ"].ToString();
lblAcres.Text = string.Format("{0} Acres", selectedParcel["ACRES"]);
lblLegal.Text = selectedParcel["LEGAL"].ToString();
if (selectedParcel["Active"].ToString() == "A")
{
lblInactive.Text = " (ACTIVE)";
}
else
{
lblInactive.Text = " (INACTIVE)";
lnkAddDocument.Visible = false;
}
}
lblCurrentUser.Text = Page.User.Identity.Name;
connection.Close();
}
else
Response.Redirect("./ParcelSearch.aspx");
}
I am receiving the following error:
Invalid attempt to read when no data is present.
I know the SQL statement used will return a record when it is used directly into sql query of database.
Thanks in advance for any advice. Should I be concerned about the lack of consistency in accessing data across the application at all? If so, should I be converting everything to LINQ? Or converting everything away from LINQ? I klnow of the existence of MVC and know I should learn it and use it, but I am too far down the path to try to convert there right now.
Change
if (selectedParcel != null)
To
if (selectedParcel.Read())
You have to read a record in the data reader before you can start pulling data. Its a forward only cursor that starts off not pointing to a record. The Read() method advances the reader by 1 and returns true/false if it was successful.
Note that it is not necessary to call HasRows if use the code above. The if block will only be entered if there is a row, if there is not then Read returns false and the block is not entered.
Edit
There are many bad practices in your code.
Use parameterized sql!! This is the most important thing you can take away here!
Wrap your connections in using blocks to ensure the connection is ALWAYS closed.
Sql code changes
String sql = ConfigurationManager.ConnectionStrings["Recorder"].ConnectionString;
using(SqlConnection connection = new SqlConnection(sql))
using(SqlCommand command = new SqlCommand("Select PARCEL, PIN_TXT, Owner, Address1, Address2, CSZ, ACRES, LEGAL, Active FROM [ParcelView] WHERE PARCEL = #pinNum", connection))
{
command.Parameters.Add(new SqlParameter("#pinNum", SqlDbType.VarChar){Value = pinNum});
connection.Open();
using(SqlDataReader selectedParcel = command.ExecuteReader())
{
if (selectedParcel.Read())
{
/*code unchanged*/
}
}
/* 1 line code unchanged*/
}
Once you have executed the command you need to actually read the data :
SqlDataReader selectedParcel = command.ExecuteReader();
if (selectedParcel.HasRows)
{
selectedParcel.Read();
....
....
I recommend you use this format for your sqlDatareader instead, as it it will parse whether results have been retrieved or not, and will automatically dispose itself on exception:
using(SqlDataReader selectedParcel = command.ExecuteReader())
{
while (selectedParcel .Read())
{
//Assign label text to results
}
}
You should Read() the SqlDataReader.
protected void Page_Load(object sender, EventArgs e)
{
var pinNum = MySession.Current.focusParcel;
if (pinNum == 0)
Response.Redirect("./ParcelSearch.aspx");
String sql = ConfigurationManager.ConnectionStrings["Recorder"].ConnectionString;
using(SqlConnection connection = new SqlConnection(sql))
{
connection.Open();
SqlCommand command = new SqlCommand("Select PARCEL, PIN_TXT, Owner, Address1, Address2, CSZ, ACRES, LEGAL, Active FROM[ParcelView] WHERE PARCEL =#PinNum ", connection);
//protect from sql injection
command.Parameters.AddWithValue(#PinNum, pinNum);
using(SqlDataReader selectedParcel = command.ExecuteReader())
{
if(!selectedParcel.HasRows)
return;
SetLabels(selectedParcel);
}
}
}
private void SetLabels(SqlDataReader selectedParcel)
{
lblPIN_Num.Text = selectedParcel["PARCEL"].ToString();
lblPIN_TXT.Text = selectedParcel["PIN_TXT"].ToString();
lblDateTime.Text = DateTime.Now.ToString("MMMM dd, yyyy");
lblOwner.Text = selectedParcel["Owner"].ToString();
lblAddress1.Text = selectedParcel["Address1"].ToString();
lblAddress2.Text = selectedParcel["Address2"].ToString();
lblCSZ.Text = selectedParcel["CSZ"].ToString();
lblAcres.Text = string.Format("{0} Acres", selectedParcel["ACRES"]);
lblLegal.Text = selectedParcel["LEGAL"].ToString();
if (selectedParcel["Active"].ToString() == "A")
{
lblInactive.Text = " (ACTIVE)";
}
else
{
lblInactive.Text = " (INACTIVE)";
lnkAddDocument.Visible = false;
}
lblCurrentUser.Text = Page.User.Identity.Name;
}
I refactor your code to look a little bit. You had different problems as not closing your Reader. You was open to sql injection, also you should transfer the connection to Db in separate class.
Below is code in which I have written only save first row value in database but when I try to save multiple row value it gives an error. I don't know how to use loop in this code and where to use loop to insert multiple rows in database at once.
How do I save DataGridView values into a SQL Server database?
private void button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("INSERT INTO datagrid (sr, name, email, tel_no) VALUES(#c1,#c2,#c3,#c4)", cs);
{
cmd.Parameters.Add(new SqlParameter("#C1", SqlDbType.VarChar));
cmd.Parameters.Add(new SqlParameter("#C2", SqlDbType.VarChar));
cmd.Parameters.Add(new SqlParameter("#C3", SqlDbType.VarChar));
cmd.Parameters.Add(new SqlParameter("#C4", SqlDbType.VarChar));
cs.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
{
if (!row.IsNewRow)
{
cmd.Parameters["#C1"].Value = row.Cells[0].Value;
cmd.Parameters["#C2"].Value = row.Cells[1].Value;
cmd.Parameters["#C3"].Value = row.Cells[2].Value;
cmd.Parameters["#C4"].Value = row.Cells[3].Value;
cmd.ExecuteNonQuery();
}
cs.Close();
}
}
}
}
There's some information that would be nice to have that you didn't put in your original question:
cs is most likely a SqlConnection, and since you say it works inserting one row I'm guessing it's a global (class level) variable and is created somewhere else. I would do a little bit differently (see my code example for the reason why).
What error are you getting? Based on the problem description, I'll bet it is a closed connection (because you're closing it at the end of your foreach code block, when you should be closing it outside the foreach code block).
So, with that said, here's something that might do the trick for you:
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
cs.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO datagrid (sr, name, email, tel_no) VALUES(#c1,#c2,#c3,#c4)", conn))
{
cmd.Parameters.AddWithValue("#C1", row.Cells[0].Value);
cmd.Parameters.AddWithValue("#C2", row.Cells[1].Value);
cmd.Parameters.AddWithValue("#C3", row.Cells[2].Value);
cmd.Parameters.AddWithValue("#C4", row.Cells[3].Value);
cmd.ExecuteNonQuery();
}
}
}
}
}
In the example above, I use using blocks for the SqlConnection and SqlCommand objects. The using block ensures that the resources are properly cleaned up when the using block is exited - this way you don't have to worry about things like when to call conn.Close(), as the using block will take care of that for you.
Also, I create the SqlConnection in the method. The connectionString in this case would be a string variable (at the class level, so all methods that need it can access it) holding the connection string.
Finally, I create the SqlCommand in the if block, which will only be entered if the !row.IsNewRow expression evaluates to true. I'm not 100% sure you can reassign values to a an existing command's parameters (most likely you can, but...)
I would also suggest including some error handling in case something goes wrong with the insert.
Hopefully this addresses the questions/issues you have. If not, please provide more detail so we can better assist you. Happy coding!
The problem is that cs is closed more times than it is opened.
You open the connection, insert, but then try to close for each iteration.
Either you should open a connection for each iteration, or you should see how to do everything with only only connection.
int ab;
int PIrowss = dataGridView2.Rows.Count;
for (ab = 0; ab < PIrowss; ab++)
{
PiCGetAutID();
purchaeOrder.pcautoid = Catget;
purchaeOrder.ponum = label119.Text;
purchaeOrder.col1 = dataGridView2.Rows[ab].Cells[0].Value.ToString();
purchaeOrder.col2 = dataGridView2.Rows[ab].Cells[1].Value.ToString();
purchaeOrder.col3 = dataGridView2.Rows[ab].Cells[2].Value.ToString();
purchaeOrder.col4 = dataGridView2.Rows[ab].Cells[3].Value.ToString();
purchaeOrder.col5 = dataGridView2.Rows[ab].Cells[4].Value.ToString();
purchaeOrder.POcSave();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.Open();
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
string sr = null;
string name = null;
string email = null;
string tel_no = null;
for (int i = 0; i <= this.DataGridView1.Rows.Count; i++) {
sr == this.DataGridView1.Rows(i).Cells(0).Value.ToString()
name == this.DataGridView1.Rows(i).Cells(1).Value.ToString()
email == this.DataGridView1.Rows(i).Cells(2).Value.ToString()
tel_no == this.DataGridView1.Rows(i).Cells(3).Value.ToString()
comm.CommandText = "insert into mytable(name,age) values('" & name & "','" & age& "')"
comm.ExecuteNonQuery()
conn.Close()
}
}
Try this and see. It should work
I'm writing a small ASP.net C# web page and it keeps giving me an error stating:
There is no row at position 0.
I'm probably doing it wrong but here is some of my code:
string SqlQuery = "SELECT * ";
SqlQuery += " FROM main_list";
SqlQuery += " WHERE ID = #FindID";
SqlConnection conn = new SqlConnection("server=???;database=contacts;User
ID=???;Password=???;");
conn.Open();
SqlCommand SqlCmd = new SqlCommand(SqlQuery, conn);
SqlCmd.Parameters.Add("#FindID",searchID);
SqlDataAdapter da = new SqlDataAdapter(SqlCmd);
try {
da.Fill(dt);
fillData(p);
}
catch {
txtId.Text = "ERROR";
}
And FillData is the following:
protected void fillData(int pos) {
txtId.Text = dt.Rows[pos]["ID"].ToString();
txtCompany.Text = dt.Rows[pos]["Company"].ToString();
txtFirstName.Text = dt.Rows[pos]["First_Name"].ToString();
txtLastName.Text = dt.Rows[pos]["Last_Name"].ToString();
txtAddress1.Text = dt.Rows[pos]["Address1"].ToString();
txtAddress2.Text = dt.Rows[pos]["Address2"].ToString();
txtCity.Text = dt.Rows[pos]["City"].ToString();
txtState.Text = dt.Rows[pos]["State"].ToString();
txtZipCode.Text = dt.Rows[pos]["ZipCode"].ToString();
txtPhoneNum1.Text = dt.Rows[pos]["Phone_Num"].ToString();
txtPhoneNum2.Text = dt.Rows[pos]["Phone_Num2"].ToString();
txtFax.Text = dt.Rows[pos]["Fax_Num"].ToString();
txtEmail.Text = dt.Rows[pos]["Email"].ToString();
txtNotes.Text = dt.Rows[pos]["Notes"].ToString();
txtCategory.Text = dt.Rows[pos]["Category"].ToString();
txtSubCategory.Text = dt.Rows[pos]["SubCategory"].ToString();
txtDateAdded.Text = dt.Rows[pos]["DateAdded"].ToString();
txtDateModified.Text = dt.Rows[0]["DateModified"].ToString();
}
Here is the call that errors out:
protected void btnPrev_Click(object sender, EventArgs e) {
p--;
lblPage.Text = p.ToString();
fillData(p-1);
}
protected void btnNext_Click(object sender, EventArgs e) {
p++;
lblPage.Text = p.ToString();
fillData(p-1);
}
I'm trying to cycle thru the Rows[0] to Rows[1] or however many there is but it gives me the error about no row at position 0 or position 1. It only fills once and then errors out.
EDIT:
I'm trying to access the second row returned by the database after already accessing one row already. For example: Rows[0] is accessible fine but then when I try to read Rows[1] it errors and says it doesn't have a row in position 1. I can revise the code to return Rows[1] and it works but when I try to access Rows[0] it breaks. This is why I pass the variable (p) to fillData so it can show only that Rows value. Thanks!
EDIT 2: I believe it's because there is a postback that wipes the values retrieved by the database. Is there a way to get the database entries to stay even after a postback? If not I am guessing I will have to query the database every time.
The error message indicates there are no rows being returned by SQL. Are you sure there is data to be returned.
When you use dt.Rows[0] you are effectively saying "take the first row that comes back, and get a value from it." If the DataTable doesn't have any rows (i.e. your SQL query returns no matches), that's like saying "Here is a plate that contains no apples. Take the first apple and tell me what colour it is" - see? Doesn't make sense.
What you should do is check whether there are any rows before you try to read them...
if(dt.Rows.Count > 0)
{
// do stuff here.
}
Use Linq and a stored procedure it is much nicer
datacontext context = new datacontext();
var result = context.MyStoredProc(searchID).FirstOrDefault();
Try changing
SqlCmd.Parameters.Add("#FindID",searchID);
to
SqlCmd.Parameters.AddWithValue("#FindID",searchID);
Check your query on your database, make sure rows are actually being returned. Also, it's bad practice to put your query directly into your code like that, especially when using parameters. You might want to try something like this:
private Int32 CallStoredProcedure(Int32 FindId)
{
using (var dt = new DataTable())
{
using (var conn = new SqlConnection(ConnectionString))
{
using (var sqlCmd = new SqlCommand("SEL_StoredProcedure", conn))
{
using (var sda = new SqlDataAdapter(sqlCmd))
{
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#FindId", FindId);
sqlCmd.Connection.Open();
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 1)
return Convert.ToInt32(dt.Rows[0]["ID"]);
else if (dt.Rows.Count > 1)
throw new Exception("Multiple records were found with supplied ID; ID = " + studentId.ToString());
}
return 0;
}
To set up your stored procedure, on your database run this:
CREATE procedure [dbo].[SEL_StoredProcedure]
#FindId int = null
as
SELECT * FROM main_list where ID = #FindId
Just remove the index identifier from the code:
e.g.
txtId.Text = dt.Rows["ID"].ToString();