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?
Related
i try to make an examining system so the admin up lode the question and the choices and the answers i wont to display in user side the question and the chooses in Multi View each view have a question and 3 Radio Button one for each chois
my code only bring me the last question in the table
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM exam WHERE exam_name='" + Request.QueryString["examid"] + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
d1.DataSource = dt;
d1.DataBind();
View view = new View();
Label label = new Label();
RadioButton RadioButtonA = new RadioButton();
RadioButton RadioButtonB = new RadioButton();
RadioButton RadioButtonC = new RadioButton();
foreach (DataRow dr in dt.Rows)
{
label.Text = dr["qustion"].ToString();
RadioButtonA.Text= dr["cha"].ToString();
RadioButtonB.Text = dr["chb"].ToString();
RadioButtonC.Text = dr["chc"].ToString();
view.Controls.Add(label);
view.Controls.Add(RadioButtonA);
view.Controls.Add(RadioButtonB);
view.Controls.Add(RadioButtonC);
m1.Views.Add(view);
}
if (!IsPostBack)
{
m1.ActiveViewIndex = 1;
}
con.Close();
You create the instance outside the loop so every time when the program enters the loop. It only rewrites the text of existing controls instead of creating new ones.That's why it seems like only the last question remains.
What you want should be like
View view;
Label label;
RadioButton RadioButtonA, RadioButtonB, RadioButtonC;
foreach (DataRow dr in dt.Rows)
{
view = new View();
label = new Label();
RadioButtonA = new RadioButton();
RadioButtonB = new RadioButton();
RadioButtonC = new RadioButton();
label.Text = dr["qustion"].ToString();
RadioButtonA.Text= dr["cha"].ToString();
RadioButtonB.Text = dr["chb"].ToString();
RadioButtonC.Text = dr["chc"].ToString();
view.Controls.Add(label);
view.Controls.Add(RadioButtonA);
view.Controls.Add(RadioButtonB);
view.Controls.Add(RadioButtonC);
m1.Views.Add(view);
}
I am using dynamic combo box in datatgridview and its populating correctly.
But when i tried to add new row for the datagridview,by clicking a button Add New Row,this combo box is repeating in cells.
If i click once , one combo box will be added in cell1,second click to add one more row,two combo box is added in cells.
How can i add new row in datagridview without repeating this combo box in cells?
My code is as follows:
private void btnRMAdd_Click(object sender, EventArgs e)
{
//add new row
dgItemGroup.Rows.Add();
fnInsertColumnsCombo();
}
private void fnInsertColumnsCombo()
{
DataGridViewComboBoxColumn combo1 = new DataGridViewComboBoxColumn();
combo1.Name = "GroupName";
combo1.HeaderText = "GroupName";
string sqlStr = "SELECT GroupID,GroupName FROM tblITEMGROUP ";
SqlCommand cmd = new SqlCommand(sqlStr, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
combo1.DataSource = dt;
combo1.DisplayMember = "GroupName";
combo1.ValueMember = "GroupID";
combo1.AutoComplete = true;
combo1.FlatStyle = FlatStyle.Flat;
dgItemGroup.Columns.Insert(0, combo1);
dgItemGroup.Columns[0].Width = 250;
}
In your method fnInsertColumnsCombo, you are adding a new column to the grid each time you add a new row. This method is called each time you add a new row. Maybe you want to add a column in the "init" phase and then populate the data after adding the new row.
I have a GridView named gridview1 and I am assigning it the data through a datatable as below.
SqlConnection con = new SqlConnection(cls_Connection.connection);
con.Open();
SqlDataAdapter sd = new SqlDataAdapter();
sd.SelectCommand = new SqlCommand("select d.id,e.Name,d.type from Employee_Details e join designation d on e.id=d.id and d.type='"+atten_cmb_type.Text+"'",con);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
The gridview contains the data and only shows it in the column when the column is clicked and hides it again. Note:I am doing all this in the ComboBox SelectedIndexChanged event.
And I had a ListView before which I deleted and used a GridView instead. All other gridviews in my application work fine.
this is my designer code
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Location = new System.Drawing.Point(456, 111);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.Size = new System.Drawing.Size(768, 315);
this.dataGridView1.TabIndex = 20;
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;
I have a webform wherein the admin will add new records to database. The form has 1 dropdownbox drpDepartments and a few textboxes EmployeeID, Fname, Lname, etc. I can add a new record but the option chosen from the dropdownbox isn't changing. It's always the first value. Here are tables tblEmployee and tblDepartment.
Here's my Page_Load() code:
sConn = new SqlConnection(sStr);
daEmp = new SqlDataAdapter("SELECT * FROM tblEmployee", sConn);
daDep = new SqlDataAdapter("SELECT * FROM tblDepartment", sConn);
dsEmp = new DataSet();
dsDep = new DataSet();
daEmp.Fill(dsEmp, "tblEmployee");
daDep.Fill(dsDep, "tblDepartment");
dsEmp.Tables["tblEmployee"].PrimaryKey = new DataColumn[] { dsEmp.Tables["tblEmployee"].Columns["EmployeeID"] };
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DataTextField = "Description";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataBind();
And the btnAdd_Click() code:
cb = new SqlCommandBuilder(daEmp);
DataRow dRow = dsEmp.Tables["tblEmployee"].NewRow();
dRow["EmployeeID"] = txtID.Text;
dRow["Lname"] = txtLname.Text;
dRow["Fname"] = txtFname.Text;
dRow["Mname"] = txtMname.Text;
dRow["Address"] = txtAddress.Text;
dRow["Email"] = txtEmail.Text;
dRow["Phone"] = Convert.ToInt64(txtPhone.Text);
dRow["Jobtitle"] = txtJobtitle.Text;
dRow["Salary"] = txtSalary.Text;
dRow["DeptID"] = drpDepartments.SelectedValue;
dsEmp.Tables["tblEmployee"].Rows.Add(dRow);
daEmp.Update(dsEmp, "tblEmployee");
dsEmp.Tables["tblEmployee"].AcceptChanges();
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test", "<script>alert('New record added!');</script>");
Refresh();
The binding of dropdown must be only in !IsPostBack
if(!IsPostBack)
{
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];// Set DataSource Table First
drpDepartments.DataTextField = "Department";// Set Column Name of DataTable to set as Text Field
drpDepartments.DataValueField = "DepartmentID";// Set Column Name of DataTable to set as Value Field
drpDepartments.DataBind();
}
If you bind the DropDownList in postback event, the dropdown will be re-binded in the the button_click (in the page_load) event and the value set by the user will be lost.