why listbox2 still empty? - c#

I can not find where is the problem, when I put while loop as a comment it works,after while loop we can not read from sqldatareader more?
listbox2 still empty!
public partial class exTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql = "select employeeid,firstname,lastname from employees";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
string item;
ListBox1.Items.Clear();
while (reader.Read())
{
item =reader.GetString(1) + reader.GetString(2);
ListBox1.Items.Add(item);
}
ListBox2.DataSource = reader;
ListBox2.DataValueField = "employeeId";
ListBox2.DataTextField = "firstname";
ListBox2.DataBind();
reader.Close();
con.Close();
}
}

You cannot use the reader again.
From the MSDN Doc
Provides a way of reading a forward-only stream of rows from a SQL Server database.
You can read one row at a time, but you cannot go back to a row once you've read the next row.
What you have to do is you have to create a list of an object (e.g. employee object) that contains employeeId, firstname, lastname. Fill the list and assign it as a source for list2 or something similar.

Related

changing my combobox list to number so i can insert it to database c#

i wanna do a combobox for the classes , when i insert the type of class in it i want to selecteditem the row that was selected exmple: i chose second row then i insert to the database a 2
sql = "insert into etudiant (Nom, prenom, sexe,classess) " +
"values(#Nom, #prenom, #sexe,#classess)"/*+"class (nom_class)" + "values(#nom_class) "*/;
cmd = new NpgsqlCommand(sql, conn);
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#nom", bunifuMaterialTextbox1.Text);
cmd.Parameters.AddWithValue("#prenom", bunifuMaterialTextbox2.Text);
cmd.Parameters.AddWithValue("#sexe", bunifuMaterialTextbox3.Text);
int id = comboBox1.SelectedIndex + 1;
cmd.Parameters.AddWithValue("#classess",Int32.Parse(comboBox1.SelectedItem.ToString()));//*/
//cmd.Parameters.AddWithValue("Num", bunifuMaterialTextbox6.Text);
//cmd.Parameters.AddWithValue("Classess", bunifuMaterialTextbox7.Text);
int result = cmd.ExecuteNonQuery();
i couldn't find a way to do it like that
i wanna find a way so i can insert to table classes int for the number of that row like the ID
For your question, you would like to achieve the current combobox selected index and insert
it into your database.
First, I want to mention that you should use comboBox1.SelectedIndex instead of comboBox1.SelectedItem.
Second, I use sqlconnection to complete the same operation, so you can modify the following code to apply to your code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connstr = #"";
SqlConnection connection = new SqlConnection(connstr);
connection.Open();
string sql = "insert into Example(Nom,Prenom,Sexe,Classess) values(#Nom,#Prenom,#Sexe,#Classess)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#Nom", textBox1.Text);
command.Parameters.AddWithValue("#Prenom", textBox2.Text);
command.Parameters.AddWithValue("#Sexe", textBox3.Text);
command.Parameters.AddWithValue("#Classess", comboBox1.SelectedIndex+1);
command.ExecuteNonQuery();
MessageBox.Show("add value successfully");
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("class1");
comboBox1.Items.Add("class2");
comboBox1.Items.Add("class3");
comboBox1.Items.Add("class4");
}
}

display results of SQL SERVER queries on one data gridview with multiple pages

i have a stored procedure with 2 queries in it, i would like to display the result of each query on its on page on a gridview. not sure how to go about this. here is an example of my stored procedure:
CREATE PROCEDURE SelectAllBeneficiaries
AS
SELECT * FROM PPRS
SELECT NAME,ID,DATE
FROM MASTERRECORDS
WHERE NAME IN (SELECT MASTERRECORDS.NAME FROM MASTERRECORDS)
GO;
here is the c# asp.net page
public partial class ExtractBeneficiaries : System.Web.UI.Page
{
string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PostbankConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// Open the SqlConnection.
SqlConnection con = new SqlConnection(strConnString);
//Create the SQLCommand object
SqlCommand command = new SqlCommand("SelectAllBeneficiaries") { CommandType = System.Data.CommandType.StoredProcedure };
SqlDataReader reader;
con.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
GridView2.DataSource = reader;
//Bind the data
GridView2.DataBind();
}
reader.Close();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
After reading first result, you can use
reader.NextResult();
to read the next result. This way you can process multiple recordset that are returned from the stored procedure.
In your case you can get the result and bind the datasource same way you have done for the first grid (GridView2).
You can read more about this at How To Handle Multiple Results by Using the DataReader in Visual C# .NET

How could I show a row from the database to a textbox in Visual Studio 2015

I just started with Visual Studio and I was wondering on how could I echo out the first row under the maincategory_name column of my maincategory table to the textbox1. I followed a guide on how to insert data through the database but what I wanted to know is how could I print out one so I'm kinda confused how will I be able to do it as for know, the output I get on my textbox is: System.Data.SqlClient.SqlCommand
namespace TrialForDatabase
{
public partial class Form1 : Form
{
SqlConnection sc = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename='C:\\Users\\flex\\Documents\\Visual Studio 2015\\Projects\\Inventory\\Inventory\\inventory.mdf';Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
textBox1.Text = cmd.ToString();
sc.Close();
}
}
}
This function first creates your SQL command, the executes it using SqlCommand.ExecuteReader(), then checks if you got any results using SqlDataReader.Read(), then displays the first column of the first row of your result to the Textbox:
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
using (var reader = cmd.ExecuteReader()){
if ( reader.Read() )
{
textBox1.Text = reader.GetString(0);
}
};
sc.Close();
}
See here for some more info on the classes used:
https://msdn.microsoft.com/de-de/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
ToString() more often that not is not redefined from Object, so it only prints the class's name.
What you want to do is print the result of your SQL command, and to do so, you will need... well, to execute it.
SqlCommand.ExecuteReader() will return a SQLDataReader object, from which you can read rows like you would with a simple array.
So if you really only want the first row, you could get away with a quick and dirty:
private void button1_Click(object sender, EventArgs e)
{
sc.Open();
cmd = new SqlCommand("SELECT maincategory_name FROM maincategory", sc);
textBox1.Text = cmd.ExecuteReader()[0];
sc.Close();
}

Getting data from MS Access database and display it in a listbox

How do I read data in ms access database and display it in a listbox. I have the codes here but i got errors.
private void button3_Click(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Sisc-stronghold\mis!\wilbert.beltran\DataBase\DataStructure.accdb"))
using(OleDbCommand cmd = new OleDbCommand(" SELECT * from TableAcct", conn))
{
conn.Open();
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
listBox1.Text = Reader.GetString("FirstName");
}
}
the errors are here:
1. Error 1 The best overloaded method match for'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments.
2. Error 2 Argument '1': cannot convert from 'string' to 'int'
try this one,
List<String> firstName = new List<String>();
List<String> lastName = new List<String>();
private void loadButton_Click(object sender, EventArgs e)
{
cn.Open();
OleDbDataReader reader = null;
cmd = new OleDbCommand("select* from Records", cn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
firstName.Add(reader["FirstName"].ToString());
lastName.Add(reader["LastName"].ToString());
}
cn.Close();
}
then in your search button, insert this,
private void searchButton_Click(object sender, EventArgs e)
{
clearSearchResult();
try
{
int totalItems = FirstName.Count;
int count = 0;
while (count < totalItems)
{
if (textBox6.Text == FirstName[count].ToString())
{
listBox1.Items.Add(FirstName[count].ToString());
count = 100;
}
else
{
count++;
}
It's good to use when you want to show the information of the "FirstName" in the listBox1_SelectedIndexChanged if you want. here's an example,
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int totalItems = lastName.Count;
int count = 0;
while (count < totalItems)
{
if ((listBox1.SelectedItem.ToString()) == firstName[count].ToString()))
{
textBox1.Text = firstName[count].ToString();
textBox2.Text = lastName[count].ToString();
count = 100;
}
else
{
count++;
}
}
hope this helps,
change
listBox1.Text = Reader.GetString("FirstName");
to
listBox1.Text = Reader.GetString(0); // zero base ordinal of column
GetString() takes an int as the parameter and not a string. Meaning that you must use the index of the column.
In your specific circumstance as "FirstName" is the second column the index would be 1:
listBox1.Text = Reader.GetString(1);
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.getstring.aspx
Thy using a While loop
while(reader.Read())
{
listbox1.Items.Add(reader["FirstName"]);
}
This moves through all the rows you selected. reader.Read() returns false if there are no more rows.
Also: if you Want to retrive valmue from a column I suggest you do it with the index ón the reader instance. Like my example.
var value = reader["ColumnName"];
This increases readability comparing to
var value = reader.GetString(0);
UPDATE
If you want to only display the fist value - I suggest you use cmd.ExecuteScalar() and the adapt you sql to only return the value you need:
using(OleDbCommand cmd = new OleDbCommand("SELECT firstname from TableAcct", conn))
{
conn.Open();
var firstName = cmd.ExecuteScalar();
}
Be aware the this will give you the first "FirstName" in the table. And since there is no "order by firstname" or "where someKey = 1" - this might not rturn that you expected.
If you want to create MS Access data base and to access it, and to display data in some component, like here i will show you.how to connect with MS Access Data Base and display data from data base in Label.
First of all create any Access data base like here "PirFahimDataBase".
Now in your Visual Studio go to the menu and do this
Click Data
Add New Data Base
Click Next
Click New Connection
Now change the Data Source by clicking Change and select Microsoft Access data base files
Click Browse for selecting your created data base
Now in Button ClickEvent paste these code which will get data from data base and will show it in the label
using System.Windows.Forms; //these two lines should be written before namespace at top of the program
using System.Data.OleDb;
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\pir fahim shah\Documents\PirFahimDataBase.accdb";
try
{
conn.Open();
MessageBox.Show("connected successfuly");
OleDbDataReader reader = null; // This is OleDb Reader
OleDbCommand cmd = new OleDbCommand("select TicketNo from Table1 where Sellprice='6000' ", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label1.Text= reader["TicketNo"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source");
}
finally
{
conn.Close();
}
}//end of button click event
Your error is in this line:
listBox1.Text = Reader.GetString("FirstName");
You must pass a number in the GetString() function.
DataColumn[] PrimaryKeyColumn = new DataColumn[1]; //Define Primary coloumn
DataSet dataSet = new DataSet();
DataTable dataTable = new DataTable();
ReadAndUpdateExcel.ReadExcel(strPath, sheetName, out dataSet);
dataSet.Tables.Add(dataTable);
PrimaryKeyColumn[0] = dataSet.Tables[0].Columns[0];
dataSet.Tables[0].PrimaryKey = PrimaryKeyColumn;
string num = dataSet.Tables[0].Rows[dataSet.Tables[0].Rows.IndexOf(dataSet.Tables[0].Rows.Find(strTCName))]["ACNO"].ToString();
//string country

sd display the details of selected item in the dropdown list from database

This is the code i have written to display the details of employee selected from the drop down list into textboxes. I didn't get any error but the details are not getting displayed in the textboxes...
protected void dlstemps_SelectedIndexChanged(object sender, EventArgs e)
{
int empno=Convert.ToInt32(dlstemps.SelectedItem.Value);
SqlConnection con = new SqlConnection();
con.ConnectionString=constr;
SqlCommand cmd=new SqlCommand();
cmd.CommandText = "select * from emp where empno="+empno;
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
txtempno.Text = reader["empno"].ToString();
txtename.Text = reader["ename"].ToString();
txtsal.Text = reader["sal"].ToString();
txtdeptno.Text = reader["deptno"].ToString();
txtadress.Text = reader["adress"].ToString();
reader.Close();
}
catch(Exception er)
{
lblerror.Text=er.Message;
}
finally
{
con.Close();
}
}
I don't understand what went wrong in this code....
Please help me to fix it.
Dropdownlist databinding
check whether databinding of dropdownlist employees dlstemps is done inside !Page.IsPostBack if block.

Categories