Connection to SQL Server through ADO.NET - Empty Listbox - c#

Trying to set up a connection to my local SQL Server Express instance so that I can display columns in a listbox. Th build runs fine and I can't see errors, but there is no data in the listbox. I have tested the query and that is fine. I am using NT Authentication to the database. Any ideas where I might have gone wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
string commstring = "Driver ={SQL Server}; Server = DESKTOP-5T4MHHR\\SQLEXPRESS; Database = AdventureWorks2014; Trusted_Connection = Yes;";
string connstring = "SELECT FirstName, LastName FROM Person.Person";
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
DataSet customerDataSet = new DataSet();
customerDataAdapater.Fill(customerDataSet, "Person.Person");
DataTable customerDataTable = new DataTable();
customerDataTable = customerDataSet.Tables[0];
foreach (DataRow dataRow in customerDataTable.Rows)
{
customers.Items.Add(dataRow["FirstName"] + " (" + dataRow["LastName"] + ")");
}
}
}

I tested your code in a sample project here and I realized you passed the parameters to SqlDataAdapter constructor in a wrong order.
After changing the follow line:
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
by
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(connstring, commstring);
the listbox was filled successfully.

Your connection string seems weird.....
Could you try using just this:
string commstring = "Server=DESKTOP-5T4MHHR\\SQLEXPRESS;Database=AdventureWorks2014;Trusted_Connection=Yes;";
Also: why are you first creating a DataSet, filling in a single set of data, and then extracting a DataTable from it?? This is unnecessarily complicated code - just use this instead:
SqlDataAdapter customerDataAdapater = new SqlDataAdapter(commstring, connstring);
// if you only ever need *one* set of data - just use a DataTable directly!
DataTable customerDataTable = new DataTable();
// Fill DataTable with the data from the query
customerDataAdapater.Fill(customerDataTable);
Update: I would really rewrite your code to something like this:
// create a separate class - call it whatever you like
public class DataProvider
{
// define a method to provide that data to you
public List<string> GetPeople()
{
// define connection string (I'd really load that from CONFIG, in real world)
string connstring = "Server=MSEDTOP;Database=AdventureWorks2014;Trusted_Connection=Yes;";
// define your query
string query = "SELECT FirstName, LastName FROM Person.Person";
// prepare a variable to hold the results
List<string> entries = new List<string>();
// put your SqlConnection and SqlCommand into "using" blocks
using (SqlConnection conn = new SqlConnection(connstring))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
// iterate over the results using a SqlDataReader
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// get first and last name from current row of query
string firstName = rdr.GetFieldValue<string>(0);
string lastName = rdr.GetFieldValue<string>(1);
// add entry to result list
entries.Add(firstName + " " + lastName);
}
rdr.Close();
}
conn.Close();
}
// return the results
return entries;
}
}
And in your code-behind, you only need to do something like this:
protected override void OnLoad(.....)
{
if (!IsPostback)
{
List<string> people = new DataProvider().GetPeople();
customers.DataSource = people;
customers.DataBind();
}
}
but I still don't understand what you were trying to when the SelectedIndexChanged event happens.....

Related

How to get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

How do I make a query to retrieve specific data

I am learning C# and SQL Server. I was following a simple tutorial, which led me to the creation of a class DBconnection that connects and updates the DB. Then I have a simple C# form that navigates back and forth on table rows using a button and a DataSet to clone the data, and then displays the info on some labels.
No problem 'till here, but then I thought, what if I wanted to display a single value(column) of a specific row, say "show me the last name of the person with a certain first name".
I'm familiar with the SQL query commands, so what I want is something like this:
SELECT last_name FROM Employees WHERE first_name = 'Jason'
Follows my code...
DBconnection.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cemiGEST
{
/// <summary>
/// A class that makes the connection to the SQL Database
/// </summary>
class DBconnection
{
// variables
private string sql_string;
private string strCon;
System.Data.SqlClient.SqlDataAdapter da_1;
// set methods
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
// DataSet
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
// MyDataSet method
private System.Data.DataSet MyDataSet()
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
// Update DB method
public void UpdateDB(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
}
I am accessing the values (when moving back and forth) by just incrementing by one a variable that updates the row number. Some exemplifying code follows.
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = Properties.Settings.Default.authSQL;
ds = objConnect.GetConnection;
maxRows = ds.Tables[0].Rows.Count;
if (maxRows == 0)
{
MessageBox.Show("No user found. Loading first run wizard.");
NewUser newUser = new NewUser();
newUser.ShowDialog();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
I'm sure this is simple, but I'm not getting there.
EDIT:
I would prefer using my class DBconnection and without external libraries. I'm not at the PC with the project, so can't test anything right now, but after a good night of sleep over the matter, and after (re)looking at my code, I may have found the answer. Please tell me if you think this would do the trick:
In my second class (where I connect to and access the DB), I have already using a SQL query, more specifically here:
objConnect.Sql = Properties.Settings.Default.authSQL;
This query (authSQL), was created by me and embedded on the Settings, and here I am importing it. So, if I do the following instead, do you think it would work:
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
The "Properties.Settings.Default.authSQL" code is nothing more than a shortcut to a string "SELECT * FROM AUTH" - AUTH is my table, which I called Employees for the sake of simplicity.
So, it would be something like this:
public partial class Example : Form
{
// variables
DBconnection objConnect;
string conStringAUTH;
DataSet ds;
DataRow dr;
int maxRows;
int inc = 0;
private void Login_Load(object sender, EventArgs e)
{
CloseBeforeLogin = true;
try
{
objConnect = new DBconnection();
conStringAUTH = Properties.Settings.Default.authConnectionString;
objConnect.connection_string = conStringAUTH;
objConnect.Sql = "SELECT last_name FROM Employees WHERE first_name = 'Jason'";
ds = objConnect.GetConnection;
// Data manipulation here
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
There's no need for a dataset here. If you know the sql you want: use it - perhaps with some parameterization. For example, using "dapper", we can do:
string firstName = "Jason";
var lastNames = con.Query<string>(
"SELECT last_name FROM Employees WHERE first_name = #firstName",
new { firstName }).ToList();
Check this ....hope this also works...
//String Declaration
string Sqlstr = "select CountryCode,Description,Nationality from ca_countryMaster where isDeleted=0 and CountryCode = 'CAN' ";
string DBCon = "Data Source=RAJA;Initial Catalog=CareHMS;Integrated Security=True;";
SqlConnection SqlCon = new SqlConnection(DBCon);
SqlDataAdapter Sqlda;
DataSet ds = new DataSet();
try
{
SqlCon.Open();
Sqlda = new SqlDataAdapter(Sqlstr, SqlCon);
Sqlda.Fill(ds);
gdView.DataSource = ds.Tables[0];
gdView.DataBind();
}
catch (Exception ex)
{
lbl.text = ex.Message;
}
finally
{
ds.Dispose();
SqlCon.Close();
}

Listbox isn't populating with Data

I have set up a listbox called lboxsupplier, i have also created a data adapter which i then used to populate the supplier listbox. When i run the form the listbox is empty. I want the listbox to populate with supplier ID and company which i will then click on to populate another listbox with products.
Namespace Pennyburn_Greg
{
public partial class FormProcess : Form
{
SqlDataAdapter daSupplier;
DataSet dsPennyburnGreg = new DataSet();
SqlConnection conn;
SqlCommand cmdSupplierDetails;
SqlCommandBuilder cmdBSupplier;
DataRow drSupplier;
String connstr, sqlSupplier;
public FormProcess()
{
InitializeComponent();
}
private void FormProcess_Load(object sender, EventArgs e)
{
connstr = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
//dataAdapter for supplier listbox
sqlSupplier = #"Select* from Supplier";
conn = new SqlConnection(connstr);
cmdSupplierDetails = new SqlCommand(sqlSupplier, conn);
daSupplier = new SqlDataAdapter(cmdSupplierDetails);
daSupplier.FillSchema(dsPennyburnGreg, SchemaType.Source, "Supplier");
}
private void filllboxsupplier(string str)
{
daSupplier.Fill(dsPennyburnGreg, "Supplier");
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"];
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
}
}
}
First of all, why are you calling FillSchema, rather should be calling Fill method to get the data, like
daSupplier.Fill(dsPennyburnGreg, "Supplier");
Once you have the dataset filled, then in your FormProcess_Load() you can add the dataset as datasource to the listbox like
lboxsupplier.DataSource = dsPennyburnGreg.Tables["Supplier"]
First thing you need to do is loosely couple your UI and data a little bit. Try this code:
// Returns a DataTable of ALL suppliers
private DataTable GetSuppliers()
{
return GetSuppliers(0);
}
// Returns a DataTable of the given supplier
private DataTable GetSuppliers(int supplierId)
{
using (var connection = new SqlCommand())
{
connection.ConnectionString = #"Data Source= arlene-pc; Initial Catalog= PennyburnGreg; Integrated Security=True";
using (var command = new SqlCommand())
{
connection.Open();
command.CommandType = CommandType.Text;
command.Connection = connection;
if (supplierId == 0)
{
command.commandText = "SELECT * FROM Supplier";
}
else
{
command.commandText = "SELECT * FROM Supplier WHERE SupplierId=#id";
command.Parameters.AddWithValue("#id", supplierId);
}
using (var adapter = new SqlDataAdapter())
{
using (var ds = new DataSet())
{
adapter.SelectCommand = command;
adapter.Fill(ds);
if (ds.Tables.Count > 0)
return ds.Tables[0];
}
}
}
}
return null;
}
And now you can just do this:
lboxsupplier.DataSource = GetSuppliers(int.Parse(lboxsupplier.SelectedValue));
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
Or if you need all Suppliers, just do this:
lboxsupplier.DataSource = GetSuppliers();
lboxsupplier.DisplayMember = "Company";
lboxsupplier.ValueMember = "SupplierID";
This code will provide some separation. This is still not ideal, but beats what you had.
You're not doing anything with the listbox control in FormProcess_Load, so it will be empty when it first loads. I'm assuming you have lboxsupplier_Click bound to the Click event of lboxsupplier? If so, then you'll need to click on that listbox before it will populate the Dataset (which is a very odd user experience, but if that's truly what you need...). If lboxsupplier_Click isn't an event handler, then you're going to have to manually call it.
If it still isn't populating, then try running your query against the database directly, and make sure that it returns data and has columns named "Company" and "SupplierID"

C# Mysql multiple queries

Im trying to build up a little status-tool. I need to get results of multiple queries (about 4-5). The general connection-setup and 'how-to-read-data' is already done but I cant figure out how the another query executed.
Everything I found while searching for it is for the SqlClient. Im totally overcharged with this.
Here is my code so far (be patient, im a newbie to this):
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC";
try
{
conn.Open();
}
catch (Exception ex)
{
listView1.Items.Add("Error: " + ex);
}
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
listMember.Add(reader["fullname"].ToString());
listOnline.Add(reader["online"].ToString());
}
conn.Close();
// SQL ENDING //
// SET ENTRIES TO LISTVIEW //
int counter = 0;
foreach(string member in listMember)
{
ListViewItem item = new ListViewItem(new[] { member, listOnline.ElementAt(counter) });
item.ForeColor = Color.Green;
listView1.Items.Add(item);
counter++;
}
}
Im not really sure how the design/layout will look like in the end, so I would like to just append the results to lists in the sql-part to process the data later out of the lists.
Do I really have to setup a complete new connection after conn.Close()? Or is there any other way? I can just imagine: 5 queries with their own connection,try,catch and 2 loops... this will get about 100-200 lines just for getting the results out of 5 queries. Isnt that a bit too much for such an easy thing?
Hope for some help.
Greetings.
According to the new comments my latest code:
Top:
public partial class Form1 : Form
{
public static string connString = "Server=10****;Port=3306;Database=e****;Uid=e****;password=****;";
public Form1()
{
InitializeComponent();
MySqlConnection conn = new MySqlConnection(connString); // Error gone!
}
Body part:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
{
try
{
MySqlCommand cmd = conn.CreateCommand(); // ERROR: conn does not exist in the current context.
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
using (conn) // ERROR: conn does not exist in the current context.
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listMember,listOnline);
//...2nd query
//QueryTwoFields("your new Select Statement", otherList, otherList);
}
}
You don't have to close connection every time you execute one query rarher than close the sqlreader assigned to that connection. Finally when all of your queries have been executed you close the connection. Consider also the use of using:
You cal also define a method for execution your Query in order for your code not to be repetive:
public void QueryTwoFields(string s, List<string> S1, List<string> S2)
///Select into List S1 and List S2 from Database (2 fields)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
S1.Add(sqlreader[0].ToString());
S2.Add(sqlreader[1].ToString());
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
if(listView1.Items.Count > 1)
{
listView1.Items.Clear();
}
var listMember = new List<string>{};
var listOnline = new List<string>{};
// SQL PART //
using (conn)
{
conn.Open();
///...1st Query
QueryTwoFields("SELECT fullname,online FROM member WHERE active = '1' ORDER BY online DESC",listmember,listonline)
//...2nd query
QueryTwoFields("your new Select Statement",myOtherList1,myOtherlist2)
....
}
}
EDIT :
Take in mind you cant define QueryTwoFields method inside button handler. You must define it outside (see code above).
Also Define your connection data in the start of the programm:
namespace MyProject
{
/// <summary>
/// Defiine your connectionstring and connection
/// </summary>
///
public partial class Form1 : Form
{ public static string connString = "Server=10*****;Port=3306;Database=e***;Uid=e***;password=********************;";
MySqlConnection conn = new MySqlConnection(connString);
.........
Datatables are fantastic
Using a data table is a nice way to do both read and write. And it comes with the luxury of eveything you can do with a datatable - like asssigning it directly to a datagrid control, sorting, selecting and deleting while disconnected.
The sample below assumes a MySqlConnection conection property managed by calls to your own OpenConnection() and CloseConnection() methods not shown.
Simple datatable read demo:
public DataTable Select(string query = "")
{
//Typical sql: "SELECT * FROM motorparameter"
DataTable dt = new DataTable();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
dt.Load(dataReader);
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return data table
return dt;
}
else
{
return dt;
}
}
In case of writing back the datatable to the database - supply the SQL you used in the read (or would have used to read to the data table):
public void Save(DataTable dt, string DataTableSqlSelect)
{
//Typically "SELECT * FROM motorparameter"
string query = DataTableSqlSelect;
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand mySqlCmd = new MySqlCommand(query, connection);
MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCmd);
MySqlCommandBuilder myCB = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = myCB.GetUpdateCommand();
adapter.Update(dt);
//close Connection
this.CloseConnection();
}
else
{
}
}
The neat thing the datatable is extremely flexible. You can run your own selects against the table once it contains data and before writing back you can set or reset what rows needs updating and by default the datatable keeps track of what rows you update in the table. Do not forget primary key column(s) for all tables in the db.
For multiple queries consider if possible using a join between the database tables or same table if data related or use a UNION sql syntax if column count and type of data is the same. You can allways "create" your extra column in the select to differ what data comes from what part of the UNION.
Also consider using CASE WHEN sql syntax to conditionally select data from different sources.

Unable to retrieve data when I use the data access layer technique dataset & adapters

I maybe approaching this the wrong way. I'm unable to retrieve data when I use the data access layer technique. If I use the following code in the main class it works:
private void button1_Click(object sender, RoutedEventArgs e)
{
myCon.connectionString();
string SomeString = string.Empty;
SomeString = "SELECT * FROM TableA";
SqlCommand cmd = new SqlCommand(SomeString, myCon.Con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "TableA");
txtID.Text = ds.Tables[0].Rows[rno][0].ToString();
txtFirstName.Text = ds.Tables[0].Rows[rno][1].ToString();
txtLastName.Text = ds.Tables[0].Rows[rno][2].ToString();
}
If I place the above code in another class I am unable to retrieve data and there are no errors.
ClassA:
public void Button(string id, string firstname, string lastname)
{
myCon.connectionString();
string SomeString = string.Empty;
SqlConnection cnn = myCon.Con;
cnn.Open();
CmdString = "SELECT * FROM TableA";
SqlCommand cmd = new SqlCommand(CmdString, cnn.Con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "Table");
id = ds.Tables[0].Rows[rno][0].ToString();
firstname = ds.Tables[0].Rows[rno][1].ToString();
lastname = ds.Tables[0].Rows[rno][2].ToString();
}
Main class:
public partial class MainWindow : Window
{
ClassA objs = new ClassA();
private void button1_Click(object sender, RoutedEventArgs e)
{
objs.Button(txtID.Text, txtFirstName.Text, txtLastName.Text);
}
Thanks in advance if anyone can help me here.
Are you trying to set the values of txtID.Text, txtFirstName.Text, etc., through your call to objs.Button?
That's an interesting approach, but it won't work as written because of the way the parameters are being passed. When you change the value of a string variable, you aren't changing the variable itself but assigning a whole new string to it. So when you reassign your parameters in your routine, you are no longer pointing to the .Text property of your controls, but to different strings. The .Text property remains unchanged.
There are several ways around this, but the simplest might be to change the signature of your subroutine:
public void Button(TextBox textId, TextBox txtFirstname, TextBox txtLastname)
{
myCon.connectionString();
string SomeString = string.Empty;
SqlConnection cnn = myCon.Con;
cnn.Open();
{
CmdString = "SELECT * FROM TableA";
SqlCommand cmd = new SqlCommand(CmdString, cnn.Con);
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "Table");
txtId.Text = ds.Tables[0].Rows[rno][0].ToString();
txtFirstname.Text = ds.Tables[0].Rows[rno][1].ToString();
txtLastname.Text = ds.Tables[0].Rows[rno][2].ToString();
}
}
Other options would be to have a series of out parameters after your input parameters. You might also be able to make it work with the ref keyword, but I'm not sure of that.

Categories