How to get the selected index or selected value of a combobox that was created by a function? I created a form and added comboboxes and textboxes. The value of a combobox affects the value of the next one and so on:
Form Edit = new Form();
ComboBox contract = new ComboBox();
ComboBox finyear = new ComboBox();
Button Update = new Button();
Button Cancel = new Button();
Label fyLbl = new Label();
Label ContractLbl = new Label();
SQLiteConnection _connection = new SQLiteConnection();
_connection = new SQLiteConnection("Data Source=mydb.db;Version=3");
_connection.Open();
string qr = "SELECT ContractId,Name FROM Contract";
using (SQLiteDataAdapter sda = new SQLiteDataAdapter(qr, _connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow dataRow = dt.NewRow();
dataRow[0] = 0;
dataRow[1] = "Select...";
dt.Rows.InsertAt(dataRow, 0);
contract.DataSource = dt;
contract.DisplayMember = "Name";
contract.ValueMember = "ContractId";
}
int contractId = contract.SelectedIndex;
The last line is always null. Comboboxes created with the Designer can work with SelectedIndexChanged but since my controls are not accessible outside this function, what can I do?
private void AutoComplete()
{
textBox4.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox4.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection col = new AutoCompleteStringCollection();
OleDbDataAdapter dAdapter2 = new OleDbDataAdapter("select ID from Car ", connParam);
OleDbCommandBuilder cBuilder2 = new OleDbCommandBuilder(dAdapter2);
DataTable dataTable2 = new DataTable();
DataSet ds2 = new DataSet();
dAdapter2.Fill(dataTable2);
foreach (DataRow row in dataTable2.Rows)
{
//TextBox1.Text = row["ImagePath"].ToString();
col.Add(row["ID"].ToString());
}
textBox4.AutoCompleteCustomSource = col;
}
I was calling this function in form load but not working
I also call the method on text_change but i faced the same problem that no values appeared
net sql server , I want a loop to retrieve data from sql database to different label controls using C# asp.net sql server storedprocedure.
string constrng = ConfigurationManager.ConnectionStrings["baby"].ConnectionString;
SqlConnection conn = new SqlConnection(constrng);
SqlCommand sqlComm;
sqlComm = new SqlCommand("stor_proc", conn);
sqlComm.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = sqlComm.ExecuteReader();
DataSet ds = new DataSet();
ds.Tables.Add("Home");
ds.Tables[0].Load(dr);
m.Text = ds.Tables[0].Rows[0][1].ToString();
i.Text = ds.Tables[0].Rows[0][2].ToString();
d.Text = ds.Tables[0].Rows[0][3].ToString();
g.Text = ds.Tables[0].Rows[0][4].ToString();
m1.Text = ds.Tables[0].Rows[1][1].ToString();
i1.Text = ds.Tables[0].Rows[1][2].ToString();
d1.Text = ds.Tables[0].Rows[1][3].ToString();
g1.Text = ds.Tables[0].Rows[1][4].ToString();
m2.Text = ds.Tables[0].Rows[2][1].ToString();
i2.Text = ds.Tables[0].Rows[2][2].ToString();
d2.Text = ds.Tables[0].Rows[2][3].ToString();
g2.Text = ds.Tables[0].Rows[2][4].ToString();
conn.Close();
for (int i = 0; i < 3; i++ ) {
m.Text = ds.Tables[0].Rows[i][1].ToString();
i.Text = ds.Tables[0].Rows[i][2].ToString();
d.Text = ds.Tables[0].Rows[i][3].ToString();
g.Text = ds.Tables[0].Rows[i][4].ToString();
}
You can use a foreach loop like this:
foreach (DataRow row in ds.Tables[0].Rows)
{
// Now here, you are iterating through a individual row.
// ItemArray gives an index position of a cell within a row.
m.Text = row.ItemArray[0].ToString();
i.Text = row.ItemArray[1].ToString();
d.Text = row.ItemArray[2].ToString();
g.Text = row.ItemArray[3].ToString();
}
Two comboBox and a table called MAINCATE is created.
I have a code , but stuck to determine what SQLQuery should i use to get the second combo box filled , determined by the first combo box.
I just need a little help on how to fill in the second combobox based on mainCate picked by the first combobox..
i need to do something like.. if combobox 1 mainCate is "Food" , then combo box 2 should show "Raw , cooked , fruits and vegetables"
This is what is inside of the MAINCATE table -
(http://i.imgur.com/qR90Z2B.png)
And this is my code :-
DataSet ds1;
DataSet ds2;
public User()
{
InitializeComponent();
}
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");
mainCatU.DisplayMember = "mainCate";
mainCatU.ValueMember = "mainCate";
mainCatU.DataSource = ds1.Tables["MAINCATE"];
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
SqlDataAdapter daSub = new SqlDataAdapter("SELECT >What should i do here?<", conn);
ds2 = new DataSet();
daSub.Fill(ds2, "Subcate");
subCatU.DisplayMember = "Subcat1";
subCatU.ValueMember = "Subcat";
subCatU.DataSource = ds2.Tables["MAINCATE"];
subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
subCatU.Enabled = true;
conn.Close();
}
private void mainCatU_SelectionChangeCommitted(object sender, EventArgs e)
{
//have no idea if a code should be here..
}
or should i do something like this?
SqlCommand cmd = new SqlCommand("select Subcat1,Subcat2,Subcat3,Subcat4 from MAINCATE where mainCate=#mainCate;", con);
=========================================
#philip -
putting this on page load repalcing my code above - it didnt work..
string result = mainCatU.SelectedItem.ToString();
SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate = " + result , conn);
ds2 = new DataSet();
daSub.Fill(ds2, "Subcate");
subCatU.DisplayMember = "Subcat1";
subCatU.ValueMember = "Subcat1";
subCatU.DataSource = ds1.Tables["MAINCATE"];
subCatU.DropDownStyle = ComboBoxStyle.DropDownList;
subCatU.Enabled = true;
even tried
SqlDataAdapter daSub = new SqlDataAdapter("SELECT * FROM MAINCATE where mainCate=#result", conn);
Actually, you don't need another sql query,because you already get all maincate records from database.You can simply use dictionary to store this records.
First define a Dictionary<string,List<string>>
Define it here(!)
DataSet ds1;
DataSet ds2;
Dictionary<string,List<string>> allRecords = new Dictionary<string,List<string>>();
Then: (i edit your code)
SqlDataAdapter daMain = new SqlDataAdapter("SELECT * FROM MAINCATE", conn);
ds1 = new DataSet();
daMain.Fill(ds1, "Maincate");
DataTable dt = ds1.Tables["MAINCATE"];
foreach (DataRow dr in dt.Rows)
{
List<string> SubCats = new List<string> {
dr["Subcat1"].ToString(),
dr["Subcat2"].ToString(),
dr["Subcat3"].ToString(),
dr["Subcat4"].ToString()
};
allRecords.Add(dr["mainCate"].ToString(),SubCats);
mainCatU.Items.Add(dr["mainCate"].ToString());
}
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
Then you need to handle mainCatU selectionchanged like this:
if(allRecords.ContainsKey(mainCatU.SelectedItem.ToString())) {
subCatU.DataSource = allRecords[mainCatU.SelectedItem.ToString()];
}
I think this is what your looking for:
Fill the first combo box with your current code.
Then to fill the second combo box you need to hook up the first combo box selectionchangecommitted. However why not just use the standard event?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Here use if statements to capture what value is set
if (comboBox1.SelectedIndex = 1)
//If selected value is Vehicles
{
//Then SELECT * FROM MainCate WHERE MainCate = 'Vehicles'
//This is possibly incorrect as I don't know how your DBTable is structured
//Same code as before
//Set this data to the second combobox
}
}
OK? So look into implementing this, if you want to refactor this you could, rather than using IF statements you could parametrise -
string result = comboBox1.SelectedItem.ToString();
SELECT * FROM MainCate WHERE MainCate = result
Obviously this won't compile so don't copy then paste it, then come back saying it doesn't work. It needs to be implemented like you did before, but rather than hardcode the result each time, use the parameter.
Personally I wouldn't have this all in one class, however you may prefer this way.
ComboBox1, ComboBox2 -- you just want to populate ComboBox2 using ComboBox1 Select change. So, At first bind your ComboBox1. Then cretae an event for ComboBox1:
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = ComboBox1 .SelectedValue.ToString();
LoadComboBox2 ();
}
And Get your ComboBox1 selected value and use it to populate ComboBox2 .
private void LoadComboBox2 ()
{
DataRow dr;
SqlConnection con = new SqlConnection(#"Data Source=name;Initial Catalog=dbName;User ID=sa;Password=sa123");
con.Open();
SqlCommand cmd = new SqlCommand("select id,name from table where id=#ID", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "--Select--" };
dt.Rows.InsertAt(dr, 0);
ComboBox2 .ValueMember = "ID";
ComboBox2 .DisplayMember = "Name";
ComboBox2 .DataSource = dt;
con.Close();
}
I'm working with GridView I need to add button to an existing column (turn an existing column to buttoncolumn) not add new column with buttons. my column called Volunteers.
see the code below:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
DataGridViewButtonXColumn bcx =
dataGridViewShowCourse.Columns["Volunteers"] as DataGridViewButtonColumn;// Like I did nothing
bcx.UseColumnTextForButtonValue = true;
bcx.Text = "ADD";
bcx.Name = "MyButton";
}
the error show: Object reference not set to an instance of an object.
I know add new column with button but I dont want do that, I need to add button to an existing column. The code for add new column with button like below
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
dataGridViewShowCourse.Columns.Add(col);
Thanks
You can add new button column before setting your DataSource with correct settings like this:
public void showCourse()
{
SqlCommand com = new SqlCommand("SELECT [Course_ID],[Course_Name],[Course_Type],[Course_Hours],[Course_Duration],[Course_Place],[Trainer_ID],[Volunteers] FROM [VolunteersAffairs].[dbo].[Course_Info]", con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats, "Course_Info");
if(dataGridViewShowCourse.Columns["MyButton"] == null){
var col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text = "ADD";
col.Name = "MyButton";
col.DataPropertyName = "Volunteers"; //<-- this is very important
dataGridViewShowCourse.Columns.Add(col);
}
dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
}
However I suggest you should remove the Volunteers from the SELECT and add the new button column yourself.
Set the column to the last:
col.DisplayIndex = dataGridViewShowCourse.Columns.Cast<DataGridViewColumn>()
.Count(col=>col.Visible) - 1;