private void PopulateComboBox()
{
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
DataTable dt;
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand("sql query here", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
ComboxBox1.ValueMember = "col1";
ComboxBox1.DisplayMember = "col2";
ComboxBox1.DataSource = dt;
}
connection.Close();
}
}
}
That above code works fine. However, I want to add a static entry at index 0 of the ComboBox1 along with the dynamic entries above from the database. The static index 0 value should be "Select a value".
How do you combine static and dynamic data in a ComboBox?
You can insert an empty record into your DataTable before binding it to ComboBox:
dt = new DataTable();
dt.Load(reader);
DataRow row = dt.NewRow();
row["col1"] = "Something";
row["col2"] = "Something else";
dt.Rows.InsertAt(row, 0);
ComboxBox1.ValueMember = "col1";
ComboxBox1.DisplayMember = "col2";
ComboxBox1.DataSource = dt;
You can try:
comboBox1.Items.Add(new ListItem("Text", "Value"))
comboBox1.Items[0].Text = "Select a value";
and in your sql code:
.......
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
comboBox1.Items.Add("col1");
...
}
Use dt.Rows.InsertAt(Datarow row, int pos) to insert a new row at position 0 before binding the combobox.
Related
How can I set the first line of Combobox empty in my code?
This is the function that is called when the form loads and it inserts the options on the Combobox.
private void preencherComboDpt()
{ carregandoComboDepartamentos = true;
NpgsqlConnection conn = new NpgsqlConnection();
try
{
conn = new NpgsqlConnection(connstring);
string query = "select * from departamento order by departamento";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
cmd.CommandText = query;
conn.Open();
NpgsqlDataReader drd = cmd.ExecuteReader();
DataTable dt = new DataTable("tabela");
dt.Columns.Add("departamento_id", typeof(int));
dt.Columns.Add("departamento", typeof(string));
while (drd.Read())
{
DataRow row = dt.NewRow();
row["departamento_id"] = int.Parse(drd["departamento_id"].ToString());
row["departamento"] = drd["departamento"].ToString();
dt.Rows.Add(row);
}
cobUnivDep.DataSource = dt.DefaultView;
cobUnivDep.DisplayMember = "departamento";
cobUnivDep.ValueMember = "departamento_id";
}
catch
{
MessageBox.Show("Error ");
}
carregandoComboDepartamentos = false;
}
I already tried inserting the line cobUnivDep.SelectedIndex = null, but it doesn't work.
I have a textbox that I'm using to search a customer from my database.
this is my code :
DataView dv = new DataView(tabSearchCustomer);
dv.RowFilter = string.Format("CONVERT({0},System.String) LIKE '%{1}%'", "ID", txtboxSearchCustomer.Text);
dgvCustomers.DataSource = dv;
dgvCustomers.DataSource = dv only shows the new data , it doesn't replace it in the dgv.
I want that my dgv will updated with the new data I was searched (replace the old data in the dgv) , how can I do that ?
My dgv before the search :
My dgv after the search :
public static DataTable ExecuteQuery(string storedProcedure, SqlParameter[] parameters)
{
using (SqlConnection sqlConnection = new SqlConnection(DLLConfig.GetDataBaseConnection()))
{
DataTable dataTable = new DataTable();
SqlCommand sqlCommand = new SqlCommand(storedProcedure, sqlConnection);
sqlCommand.CommandTimeout = 0;
sqlCommand.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter param in parameters)
{
sqlCommand.Parameters.Add(param);
}
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dataTable);
SqlConnection.ClearAllPools();
return dataTable;
}
}
Usage:
dataGridView1.DataSource = ExecuteQuery().DefaultView;
I have datagridview, that i must fill by 5 tables. I declared SqlCommand and SqlConnection.
After that I use somethine like this:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = selCommand;
ad.Fill(dt);
dataGridView1.DataSource = dt;
As a result I have column headers of my query in datagridview, but don't have data.
I tried use this code:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataReader dr = selCommand.ExecuteReader();
dt.Load(dr);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dr.Close();
It was working, but I something change and I can't understand why it does not work.
Try this:
DataTable table = null;
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
try
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Something WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#Id", YourValue));
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
table = new DataTable();
adapter.Fill(table);
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
dataGridView1.DataSource = table;
This is my code. After adding data through DataSource, The SelectedIndexChanged event is not firing.
try
{
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//comboBox1.Items.Clear();
comboBox1.ResetText();
Cn.Open();
SqlCommand Cd = new SqlCommand("Select Distinct Mobile From Client_Details Where Branch = '" + label2.Text + "'", Cn);
SqlDataReader da = Cd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
dt.Load(da);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
}
finally
{
Cn.Close();
Clear();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Label CBSL = new Label();
//string CBSL = this.comboBox1.SelectedItem.ToString();
if (comboBox9.Text == "Client")
{
Update_Read_Client();
}
else if (comboBox9.Text == "Customer")
{
Update_Read();
}
}
It selects the first value again and again.
I had tried DropDownStye = DropDownList., But it become dormant. No values is added.
Any help to resolve my problem.
I'm not sure if you have "< Select >" item saved in your database. Also, when using DataTable it's easier to fill it using SqlDataAdapter. You should also use parameters instead of string concat when you're writing your query like this and using keyword closes your connection automatically when you're done using it. I'd write it like this probably:
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT DISTINCT Mobile
FROM Client_Details
WHERE Branch = #Branch";
cmd.Parameters.AddWithValue("#Branch", label2.Text);
try
{
var dt = new DataTable();
dt.Columns.Add("Mobile", typeof(string));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
DataRow row = dt.NewRow();
row["Mobile"] = "<Select>";
dt.Rows.InsertAt(row, 0);
comboBox1.DisplayMember = "Mobile";
comboBox1.DataSource = dt;
comboBox1.SelectedItem = "<Select>";
}
catch
{
throw;
}
}
I'm having a problem with a couple of gridviews that are filled from the code behind.
When I fill and databind GridView1 on it's own it works fine.
I then added the code to fill and bind GridView2 which displays but GridView1 dissapears completely.
If I comment out GridView2.DataBind() then GridView1 then appears again.
I can't work out what is going on.
Incidentaly if I change GridView2 for a DropDownList or a CheckBoxList then the same problem occurs, but if I change it for a ListBox then GridView1 appears.
protected void Page_Load(object sender, EventArgs e)
{
Int32 chaID = 20;
Int32 slots = 14;
String ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
String selectSQL = "SELECT chassis.ChassisName, srv.ChassisPosition, srv.ServerName, srv.ChassisID, srv.LocationID, chassis.LocationID AS ChaLocationID FROM srv INNER JOIN chassis ON srv.ChassisID = chassis.ChassisID WHERE (srv.ChassisID = '" + chaID + "') ORDER BY chassis.ChassisName, srv.ChassisPosition";
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
DataTable dt2 = new DataTable();
DataView dv = new DataView();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt2);
dv = dt2.DefaultView;
}
catch (Exception)
{
}
try
{
int searchIndex;
dv.Sort = "ChassisPosition";
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Bay", typeof(Int32)));
dt.Columns.Add(new DataColumn("Server", typeof(String)));
for (int i = 0; i <= slots - 1; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i + 1;
searchIndex = dv.Find(i + 1);
if (searchIndex != -1)
{
dr[1] = dv[searchIndex][2].ToString();
}
else
{
dr[1] = "-----";
}
dt.Rows.Add(dr);
}
this.GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
}
ConnectionString = WebConfigurationManager.ConnectionStrings["horizonConnectionString"].ToString();
selectSQL = "SELECT [ServerName], [ServerID], [FarmName], [LMG] FROM [srv] ORDER BY [ServerName]";
con = new SqlConnection(ConnectionString);
cmd = new SqlCommand(selectSQL, con);
DataTable dt3 = new DataTable();
try
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
sda.Fill(dt3);
this.GridView2.DataSource = dt3;
GridView2.DataBind();
}
catch (Exception)
{
}
}
you are using the same instance of SqlDataAdapter for two connections at the same time.
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
the SqlDataAdapter object has been named "sda" twice in "page_load" method.
SqlDataAdapter sda = new SqlDataAdapter(selectSQL, con);
SqlDataAdapter "sda" is already binding to GridView1. this data binding will be lost if U change or re-assign this object.