I want insert some data to localdatabace and insert is successfully done but don't show in my datagridview tile second insert do for debog it I Call Select All end of my insert and see the last insert don't show in it but whene i insert a next data , last data will be showing can every one help me pleas?
public void connect()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(conString);
String sqll = "Insert into TblBank (txtTodayDate" +
",txtSahebanHesab" +
",txtShobe" +
",txtShomareMoshtari" +
",txtShoareHesab" +
",cmbNoeHesab" +
",txtSarresid" +
")";
try
{
sql.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqll, sql);
SqlCommand sc = new SqlCommand(sqll,sql);
sc.Parameters.AddWithValue("todayDate", new PersianDateTime(dtpTodayDate.the_date).ToString("yyyy/MM/dd"));
sc.Parameters.AddWithValue("sahebanHesab", txtSahebHesabName.Text);
sc.Parameters.AddWithValue("shobe", txtshobe.Text);
sc.Parameters.AddWithValue("shomareMoshtari", txtShomareMoshtari.Text);
sc.Parameters.AddWithValue("shoareHesab", txtShomareHesab.Text);
sc.Parameters.AddWithValue("noeHesab", cmbNoeHesab.SelectedIndex);
sc.Parameters.AddWithValue("sarresid", txtSarResidMah.Text);
sc.ExecuteNonQuery();
sql.Close();
select();
}
catch (Exception ex)
{
}
}
and select is
private void select()
{
String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\hana\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection cn = new SqlConnection(conString);
String sqlString = "SELECT * FROM TblBank Order BY Id desc ";
SqlConnection sql = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(sqlString, cn);
try {
sql.Open();
SqlDataAdapter sa = new SqlDataAdapter(sqlString, sql);
using (SqlDataReader read = sa.SelectCommand.ExecuteReader())
{
if (read.Read())
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
sql.Close();
}
catch (Exception ex)
{
}
}
The DataReader.Read() method will iterate result set before DataTable.Load(). Because the DataReader is a forward-only stream, it has empty result set when DataTable.Load() executes and DataTable content is still empty while setting DataSource for DataGridView. Try DataReader.HasRows property to check result set availability:
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(sqlString, cn))
{
try
{
cn.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
// check if the reader returns result set
if (read.HasRows)
{
DataTable dt = new DataTable();
dt.Load(read);
this.tblBankDataGridViewX.DataSource = dt;
}
}
}
catch (Exception ex)
{
// do something
}
}
}
Related
I Inserted Data to ComboBox using Folloowing Code in FormLoad Block
try
{
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form. I used the following code to Delete and Load the items to ComboBox after Deleting.
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
try
{
SelectCategoryComboBox.Items.Clear();
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
code for Creating new item Given below
if (CategoryNameText.Text == "")
{
StatusLabel.Text = "You have to provide a name to create a category";
}
else
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";
try
{
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = "An Error Occured while Loading Data!";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
CategoryNameText.Focus();
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = ("An ERROR occured While creating category!");
}
finally
{
CategoryNameText.Text = "Enter Category Name";
}
}
}
This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox, it does the Job i.e it deletes and Load the Remaining items to ComboBox.but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox.
I find the problem occur in the following sentence.
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
I have two solutions.
First, Please set the Allow nulls for other field.
Like the following:
Second, you can use the following code to replace the original code.
string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);
I found What went Wrong...
Change Following Code
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
To
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string squery = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
it Worked for me.
I am trying to show Oracle Data in a DataGridView in my Windows Form Application but it just returns a grey blank view. My code for this currently is:
string insertquery = "select * from Candidate where CandidateName like '"+ txtBoxSearchData.Text +"%'";
OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = insertquery;
try
{
OracleDataReader reader = cmd.ExecuteReader();
OracleDataAdapter orada = new OracleDataAdapter(cmd);
DataTable dataTable = new DataTable();
orada.Fill(dataTable);
dataTable.Load(reader);
BindingSource bSource = new BindingSource();
bSource.DataSource = dataTable;
dataGridViewSearch.DataSource = bSource;
orada.Update(dataTable);
}
catch(ArgumentException ex)
{
MessageBox.Show("Error: " + ex.Message);
}
catch(OracleException ex1)
{
MessageBox.Show("Error: " + ex1.Message);
}
finally
{
cmd.Dispose();
con.Dispose();
}
}
I am positive I do not require all those functions in my Try statement but I have come across many different methods to do this - I just included all of those into my code to experiment. The connection string is correct too as I have succeeded in adding data into the tables through queries in another part of my application.
Doing something like the following should be enough. There should be no need for an OracleDataAdapter or BindingSource. Just can't test it here, as I do not have an Oracle database around.
public void fillDataGrid()
{
try
{
using(OracleConnection connection = new OracleConnection("connectstring"))
using(OracleCommand cmd = new OracleCommand("select * from my super table", connection ))
{
connection .Open();
using(OracleDataReader oracleDataReader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(oracleDataReader );
myDataGrid.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This is what I have so far:
static void Main(string[] args)
{
DataTable t = new DataTable();
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
cnn = new SqlConnection(connetionString);
string sql = "SELECT * FROM shiplabels";
SqlDataAdapter a = new SqlDataAdapter(sql, cnn);
try
{
cnn.Open();
a.Fill(t);
cnn.Close();
}
catch (Exception ex)
{
Console.WriteLine ("Can not open connection ! ");
}
}
I want to connect to this Microsoft DB and pull data from it. I am having trouble just getting this to work! When I use this code datatable t has 0 rows where it should come back with a few hundred. I'm clearly missing something simple here?
DataTable dt = new DataTable();
SqlDataAdapter sqlAdtp = new SqlDataAdapter();
string connectionString = "Data Source=local.url;Initial Catalog=databasename;User ID=username;Password=password";
string sql = "SELECT * FROM shiplabels";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
try
{
sqlAdtp.SelectCommand = cmd;
sqlAdtp.Fill(dt);
}
catch (Exception ex)
{
}
}
}
First, you don't need to open the connection when using SqlDataAdapter.
Also, you forgot the CommandType.
This should work fine for you.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";
sqlCnn = new SqlConnection(connetionString);
try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}
I want to display the items in my database inside the combo box after the radio option is been selected. when i tried this nothing was displayed in the combo box. please kindly help
private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
Your try block should resemble the following:
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
DataTable dt = new DataTable();
//Put some data in the datatable!!
using(OleDbDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
cmbDisplay.Items.Add(dt.Rows[i]["SeatNo"]);
}
}
You need to fill your DataTable with data!
You might also consider the following:
using(OleDbDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
This way you don't even need to use a DataTable; this is a more efficient approach for large sets of data.
As an aside, you may wish to consider using Using:
using(OleDbConnection connect = db.dbConnect())
{
try
{
connect.Open();
//MessageBox.Show("Opened");
using(OleDbCommand command = new OleDbCommand())
{
command.Connection = connect;
command.CommandText = "SELECT * FROM Categories";
using(IDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
cmbDisplay.Items.Add(reader.GetValue(reader.GetOrdinal("SeatNo"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("An erorr occured:" + ex);
}
}
This will ensure your connection, command and reader objects are disposed. This is not appropriate if you intend to hold onto an instance of your connection however as it will be closed AND disposed as soon as your code leaves the using statement.
There is missing filling DataTable dt with datas, which are returned by your sql command.
try with this code - in your sample you don't bind your table with data, you create new instance of table.
$ private void chkDetailsButton_Click(object sender, EventArgs e)
{
if (radioButtonA.Checked)
{
OleDbConnection connect = db.dbConnect();
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
cmbDisplay.Items.Add(myReader["SeatNo"]);
}
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}
}
I can't believe this. :D
When are you exactly filling the DataTable with data from DB?
There is nothing in between
DataTable dt = new DataTable();
and
for (int i = 0; i < dt.Rows.Count; i++)
you can fill combobox with Datatable :
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from Books",con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
comboBox1.DataSource = dt;
You are not filling data in Dataset before attaching try this
if(radio.checked)
{
try
{
connect.Open();
MessageBox.Show("Opened");
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "Select * from Categories";
OleDbDataAdapter db = new OleDbDataAdapter();
DataSet ds = new DataSet();
db.SelectCommand = command;
db.Fill(ds);
for(int i=0;i<ds.Tables[0].Rows.Count;i++)
{
cmbDisplay.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
cmDisplay.DataBind();
}
catch (Exception ex)
{
MessageBox.Show("Exception in Database" + ex);
}
finally
{
connect.Close();
}
}