Please help when i insert a new data to the database it is not showing in the comboBox unless i restart the program. Is something missing from this ?
CmbSupp.Items.Clear();
con.Open();
Refresh();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select SupplierName from SuppTbl";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
CmbSupp.Items.Add(dr["SupplierName"].ToString());
}
con.Close();
Thankyou in advance!
Change
CmbSupp.Items.Clear()
To CmbSupp.Items = null;
this is a small Bug,You have to set Null Value and Reset Data;
Try It;
You could do this:
DataTable dt = new DataTable();
private void RefreshData()
{
dt.Clear();
con.Open();
Refresh();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select SupplierName from SuppTbl";
cmd.ExecuteNonQuery();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
con.Close();
cmd.Dispose();
}
private void BindToComboBox()
{
CmbSupp.DataSource = dt;
CmbSupp.ValueMember = "SupplierName";
CmbSupp.DisplayMember = "SupplierName";
}
Ideally, you include the table's ID and put it in ValueMember property. You call the Bind ToComboBox once and just call RefreshData() when there's changes in the database. It should automatically update the contents of the combobox.
Related
I want to retrieve data from postgres db into textbox in C# without using grid.
Here is the running successful code by using grid which I had tried:
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT * FROM student_folio";
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cmd.Dispose();
connection.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
I get error when build when I want to retrieve it into textbox:
"cannot apply indexing with [] to an expression of type 'NpgsqlDataAdapter'"
Here is my block of code:
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
txtFname.Text = da["f_name"].ToString();
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
A DataAdapter is not an array of rows you can loop into.
Look at your first code block : you must fill a DataTable from your adapter and then read through the Rows property of this DataTable.
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
txtFname.Text = dt.Rows[0]["f_name"].ToString();
}
You could also do this :
foreach (System.Data.DataRow row in dt.Rows)
{
txtFname.Text = row["f_name"].ToString();
}
And please, remove the cmd.ExecuteNonQuery(); line, it is useless here
try this . .
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
NpgsqlDataReader dr=null;
cmd.Connection = connection;
cmd.CommandText = ("SELECT f_name FROM student_folio WHERE id = 1");
cmd.CommandType = CommandType.Text;
dr=cmd.ExecuteReader();
while(dr.HasRows)
{
while(dr.Read())
{
txtFname.Text = da["f_name"].ToString();
}
}
connection.Close();
Good day.
I just looking for a solution to my problem. I just trying to make my first program and I have encountered this problem. I have 2 comboboxes, the first one is the list of supplier and the second one is the list of items. Now I need to filter down what will show in the 2nd combobox based on the 1st combobox, but still in the 2nd combobox. It always shows all the item that is listed from my database. All data are coming from SQL Database and below is the code that I am working with:
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
Try to clear the items before the loop.
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.
I have table consisting columns(....,....,....,BLOCK) in my database.
The BLOCK column has bit datatype(True,False).
When BLOCK column has False, the data should be fetched from the database.
When BLOCK column has True, the data should not be fetched resulting in throwing an error.
When I give the name of a particular person in textbox and click button, the above operation must be performed
my button click c# coding is...
protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
{
string selectsql = "SELECT * FROM UserDetailsTwo";
using (SqlConnection con = new SqlConnection(#"Data Source=ENTERKEY001;Initial Catalog=ContactManagement;Integrated Security=True"))//DataBase Connection
{
SqlCommand selectCommand = new SqlCommand(selectsql, con);
con.Open();
SqlDataReader SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Boolean BLOCK = Convert.ToBoolean(SelectReader["BLOCK"]);
if (BLOCK == false)
{
//con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
SelectReader.Close();
}
}
You are trying to use an SQLDataReader like a DataAdapter.
SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Int64 BLOCK = Convert.ToInt64(SelectReader["BLOCK"]);
if (BLOCK == false)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader%28v=vs.110%29.aspx
I have a combobox having the requisition number. now when i select 1 of the requisition item like r001 in the combobox its information should be populated in the datagrid below. i have used a stroed procedure for this. but i dont know how to bind the datagrid view control to the info.
code:
private void cmbreqno_SelectedIndexChanged(object sender, EventArgs e)
{
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
txtcc.Text = "";
int selection = Convert.ToInt16(((KeyValuePair<string, string>)(cmbreqno.SelectedItem)).Key);
if (selection.ToString() != "")
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "itemname";
cmd.Parameters.AddWithValue("#req_no", selection);
dsitemname.Clear();
adp = new SqlDataAdapter(cmd);
adp.Fill(dsitemname);
txtcc.Text = dsitemname.Tables[1].Rows[0]["costcenter_no"].ToString();
txtcc.Tag = dsitemname.Tables[1].Rows[0]["costcenter_id"].ToString();
cmd.Parameters.Clear();
}
stored procedure:
alter proc itemname
(
#req_no int
)
as begin
select item_name,brand_name,quantity,requisitionitem.item_cost
from requisitionitem left outer join item
on requisitionitem.item_id=item.item_id
where requisitionitem.req_no=#req_no
end
Just databind your DataTable to DataGridView
dataGridView1.DataSource = null; //clear old one
dataGridView1.Rows.Clear(); //remove old rows
dataGridView1.DataSource = dsitemname.Tables[0];
It should be as follows:
con.Open();
int selection = Convert.ToInt16(((KeyValuePair<string, string>)(cmbreqno.SelectedItem)).Key);
cmd = new SqlCommand("storedProcedureName", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#req_no",selection);
da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
cmd.ExecuteNonQuery();
Hope Its Helpful.