Oracle Connection from C# not reading data - c#

So the following code will not enter the loop to populate my list box. My list box shows "Select All" and test outputs "entering loop". What would cause the try not to fail but the loop not to execute either?
conn.Open();
OracleCommand executeQuery = new OracleCommand(sql, conn);
executeQuery.CommandType = CommandType.Text;
OracleDataReader dr = executeQuery.ExecuteReader();
lstInstructors.Items.Clear();
lstInstructors.Items.Add(new ListItem("Select All", "%"));
string test = "entering loop";
while (dr.Read())
{
test = "start reading items";
lstInstructors.Items.Add(new ListItem(dr.GetValue(0).ToString()));
test += dr.GetValue(0).ToString();
}

Where is the value for "sql" set?
A different way to accomplish populating populating a list box would be to fill a data table then bind it to the list box.
OracleDataAdapter da = new OracleDataAdapter();
DataTable dt = new DataTable();
var sql = "some sql string";
OracleCommand executeQuery = new OracleCommand(sql, conn);
using (da = new OracleDataAdapter(executeQuery))
{
da.Fill(dt);
}
lstInstructors.DataSource = dt;
lstInstructors.DataTextField = "Field Name from sql";
lstInstructors.DataValueField = "Field Value from sql";
lstInstructors.DataBind();
lstInstructors.Items.Insert(0, new ListItem("Choose", "Choose"));
lstInstructors.SelectedValue = "Choose";
be sure to include using System.Data
I've adapted this from the SqlDataAdapter so there may be some syntax differences.

Related

C# with SQL: Populating multiple comboboxes each with different columns of same table

as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table
I don't have the actual source codes with me but I was able to populate one combobox with something like
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:
myCMB.DataSource = new BindingSource(da, "Column_Name");
but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)
So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.
Use a copy of the datatable:
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt.Copy();
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
Try this:
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Display");
string query = #"SELECT ID AS ID, Description AS CODE FROM [Tender] ORDER BY ID";
SqlDataReader sqlReader = new SqlCommand(query, DB.SQLConnection).ExecuteReader();
while (sqlReader.Read())
{
if (!string.IsNullOrEmpty(sqlReader["CODE"].ToString()))
dt.Rows.Add(sqlReader["ID"].ToString(), sqlReader["CODE"].ToString());
}
cbPayment1.DisplayMember = "display";
cbPayment1.ValueMember = "value";
cbPayment1.DataSource = dt;

Not able to fill combo box dynamically in c#.net

i am writing the below code to get the data in the combo box but it does not show any data in the combo box so please help..... below is my code for filling combo box..
string qry = "select ctid,city from city order by city";
cmd = new SqlCommand(qry, con);
ds.Clear();
ad = new SqlDataAdapter(qry,con);
ad.Fill(ds);
MessageBox.Show(ds.Tables[0].Rows[1]["city"].ToString());
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "city";
comboBox1.ValueMember = "ctid";
in the messagebox after the ad.fill(ds) i can see the value inside the table but it is not reflecting in the combo box...
I have used the same logic in my app just the difference was to specify the CommandType property as 'Text' and CommandText property as the query, in SqlCommand.
var sqlDs = new DataSet();
var sqlComm = new SqlCommand();
sqlComm.Connection = sqlCon;
sqlComm.CommandType = CommandType.Text;
sqlComm.CommandText = query;
sqlDa = new SqlDataAdapter(sqlComm);
sqlDa.Fill(sqlDs);
Also when you are specifying the display member and Value member then no need to specify the columns in select query, it still work. only for the performance basis you can specify the columns name.

How do i bind data source to a ComboBox?

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference
Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer

datagrid not getting displayed

I am trying to display the data from sql into a datagrid as follows:
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = #"Data Source=servername; Trusted_Connection=yes; Database=master";
xconn.Open();
string s = "select * from tablename where name=#name";
SqlCommand ycmd = new SqlCommand(s, xconn);
ycmd.Parameters.Add("#name", dropdownlistname.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(ycmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch (Exception e2)
{
lblresult.Text = e2.Message + "<br />" + e2.StackTrace ;
}
I do not get any exception . However , the grid is not displayed.
try like this....
you can change this depends on your requirement ....
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Product WHERE Product.ID=#PROD_ID";
command.Parameters.Add(new SqlParameter("#PROD_ID", 100));
// Execute the SQL Server command...
SqlDataReader reader = command.ExecuteReader();
DataTable tblProducts = new DataTable();
tblProducts.Load(reader);
foreach (DataRow rowProduct in tblProducts.Rows)
{
// Use the data...
}
It doesn't work because you are defining a parameter #name to your sql statement but you are never feeding any value since the version of SqlCommand.Parameters.Add that takes 2 parameters is the one that receives parameterName and SqlDbType
I am surprised you are not getting exceptions. Perhaps your dropdownlistname.SelectedValue matches one of the enumeration values for SqlDbType and that's why?
You should be doing:
ycmd.Parameters.AddWithValue("#name", dropdownlistname.SelectedValue);

Binding database data to the GridView in ASP.Net

I try to bind database data to the gridview in c# and asp.net. But I couldn't see the datas in the gridview.Rows are added to the gridview but they are empty. When I run that query in SQLServer, it gives the correct result.I didn't add or change any code to the asp part.Should I? I couldn't find where is the problem :( please help..
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
command = new SqlCommand();
connect.Open();
command.Connection = connect;
string komut = "SELECT K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi FROM OduncIslemleri O,Kitap K WHERE O.kullaniciId=" + Session["id"] + " AND O.kitapId = K.id;";
try
{
SqlCommand sqlCommand = new SqlCommand();
sqlCommand = connect.CreateCommand();
sqlCommand.CommandText = komut;
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, connect);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Create a DataTable to hold the query results.
DataTable dTable = new DataTable();
//Fill the DataTable.
sda.Fill(dTable);
GridView1.DataSource = dTable;
GridView1.DataBind();
}
catch (SqlException)
{
//Console.WriteLine(e.StackTrace);
}
reader.Close();
connect.Close();
Here is the correct answer :
myConnection = WebConfigurationManager.ConnectionStrings["KutuphaneConnectionString"].ConnectionString;
connect = new SqlConnection(myConnection);
string sorgu = "select K.ad,K.yazar,K.baskiNo,O.sonTeslimTarihi from Kitap K, OduncIslemleri O where O.kitapId = K.id and O.kullaniciId = "+ Session["id"];
SqlDataAdapter sadp = new SqlDataAdapter(sorgu, connect);
DataSet ds = new DataSet();
sadp.Fill(ds);
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
connect.Close();
I also used template fields in Gridview. Also autogeneratedFields should be true. I hope this helps to the people who have the same problem
watch for another event triggered after the bind that could be clearing the rows
Try creating a DataSet and populate that using Fill instead. I've never seen Fill used on a DataTable - and can't find that particular overload on MSDN. My suspicion is, though, that such an overload would not modify the existing schema of the DataTable (which, since it's only just been created prior to use in your example, would mean that it has no columns).
I think you have to use a BindingSource Control, you set the DataSource of it to the DataTable, and then set the GridView's DataSource to the BindingSource.

Categories

Resources