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.
Related
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?
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 table tblDepartments with columns DeptID, Department, Description. I also have dropdownbox drpDepartments. I want to display the contents of column Department on the dropdownbox. I tried using this C# code for winforms but it didn't work:
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DeptID";
drpDepartments.Text = "Choose Department";
How do I do it using ASP.NET C#? Thanks.
New code (still not working)
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"] };
DataTable dt=new DataTable();
daDep.Fill(dt);
drpDepartments.DataTextField = "Department";
drpDepartments.DataValueField = "DeptID";
drpDepartments.DataSource = dt;
drpDepartments.DataBind();
You have to call it like this in asp.net webForms
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();
You must be using it from using System.Web.UI.WebControls; namespace. It seems like you were using winforms namespaces.
DataTextField is equivalent to DisplayMember and ValueMember is equivalent to DataValueField.
Did you call DataBind()?
drpDepartments.DataSource = dsDep.Tables["tblDepartment"];
drpDepartments.DisplayMember = "Department";
drpDepartments.ValueMember = "DepartmentID";
drpDepartments.Text = "Choose Department";
drpDepartments.DataBind();
drpDepartments.DataSource = ds1;
drpDepartments.DataTextField = "textcol";
drpDepartments.DataValueField = "valuecol";
drpDepartments.DataBind();
after doing this in btn_save method
add this..
cmd.Parameters.AddWithValue("#a", drpDepartments.SelectedValue);
hope it helps.
I'm new developing and I need a detailed answered, I'm sorry for my bad english...
I will try to explain myself the best I can..
I've 2 tables in Mysql
table1: id_ticket , ticket_description, ticket_status(id_status)
table2 : id_statu , status_name
In my application I use all the information inside table1 to fill a DataGridView, also I've added a comboBox column, the combobox displays "status_name" from table2, I want to modify ticket_status with the information contained in the comboBox, how can I do that?
this is my code:
public void CreateAssignedToMe(string ConnString)
{
string assignedTo = textBoxUid.Text;
string query = "SELECT * FROM reports WHERE ticket_assignee='"+assignedTo+"' AND ticket_resolution < 3;";
AssignToMe = new AssignedToMe();
AssignToMe.ConnString = ConnString;
DataGridView dgvReports = AssignToMe.dataGridViewAssignedToMe;
try
{
MySqlConnection conn = new MySqlConnection(ConnString);
conn.Open();
MySqlDataAdapter daUsers = new MySqlDataAdapter(query,ConnString);
DataSet dsUsers = new DataSet();
daUsers.Fill(dsUsers,"report");
dgvReports.DataSource = dsUsers;
dgvReports.DataMember = "report";
dgvReports.AllowUserToAddRows = false;
dgvReports.AllowUserToDeleteRows = false;
dgvReports.Columns["ticket_departmentResponsive"].Visible = false;
dgvReports.Columns["ticket_assignee"].Visible = false;
string queryStatus = "SELECT * FROM status";
MySqlDataAdapter daStatus = new MySqlDataAdapter(queryStatus, ConnString);
DataSet dsStatus = new DataSet();
MySqlCommandBuilder builder = new MySqlCommandBuilder(daStatus);
daStatus.Fill(dsStatus, "Resolution");
daStatus.UpdateCommand = builder.GetUpdateCommand();
DataGridViewComboBoxColumn cbbox = new DataGridViewComboBoxColumn();
BindingSource StatusBindingSource = new BindingSource();
StatusBindingSource.DataSource = dsStatus;
StatusBindingSource.DataMember = "Resolution";
cbbox.HeaderText = "Resolution";
cbbox.DropDownWidth = 90;
cbbox.DataSource = StatusBindingSource;
cbbox.DisplayMember = "status_name";
dgvReports.Columns.Add(cbbox);
AssignToMe.ShowDialog();
}
catch(MySqlException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
I'm not able to post Images :(
You have to add DataGridView.CellValueChanged Event. Function assigned to that event will be executed when you change any cell value.
// adding event handler (somewhere after dgvReports initialization)
dgvReports.CellValueChanged += new DataGridViewCellEventHandler(dgvReports_CellValueChanged);
// function that handles event
private void dgvReports_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// `e` argument will contain e.RowIndex and e.ColumnIndex properties
// they may be used to determine which particular cell was changed
}
In event handler you should check what column/cell was changed (row and cell index should be passed thru DataGridViewCellEventArgs e argument to your method that handles CellValueChanged event).
After that check - you should "do your update".
The scenario is almost the same as http://arsalantamiz.blogspot.com/2008/09/binding-datagridview-combobox-column.html. but I can't get it working on c#...
I have mySql db with two tables:
1. protocols
2. pcapdata
In protocols tables I have a two fields: idprotocols and protocolName
Int the pcaps table I have wizardProtocol (which is "linked" to the idprotocols field)
What I'm trying to get is to have a combobox containing names which will replace the wizardprotocol field. Next, If the user updates the "names" combobox the wizardProtocol will be changed accordingly (so I will be able to update the changes in the database accordingly).
Now, after reading some information on the net: I've written the following code:
public void Bind(ref DataGridView dataGridView)
{
try
{
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.Columns["length"].ReadOnly = true;
dataGridView.Columns["length"].DefaultCellStyle.ForeColor = System.Drawing.Color.SandyBrown;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = bindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
}
catch (System.Exception e)
{
MessageBox.Show(e.ToString());
}
}
I'm trying to manipulable the DisplayMember property, but I fail (I know that the problem is with probably with my data-binding, but I can't figure it out...)
UPDATE: Thanks to the answer, I'm re-attaching the fixed code
mySqlDataAdapter = new MySqlDataAdapter(SELECT_ALL_PCAP, _con);
mySqlCommandBuilder = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mySqlCommandBuilder.GetUpdateCommand();
mySqlDataAdapter.DeleteCommand = mySqlCommandBuilder.GetDeleteCommand();
mySqlDataAdapter.InsertCommand = mySqlCommandBuilder.GetInsertCommand();
dataSet = new DataSet();
mySqlDataAdapter.Fill(dataSet, "pcap");
MySqlDataAdapter adp2 = new MySqlDataAdapter(SELECT_ALL_PROTOCOL, _con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adp2);
adp2.UpdateCommand = builder.GetUpdateCommand();
adp2.DeleteCommand = builder.GetDeleteCommand();
adp2.InsertCommand = builder.GetInsertCommand();
adp2.Fill(dataSet, "protocol");
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
BindingSource wizardBindingSource = new BindingSource();
wizardBindingSource.DataSource = dataSet;
wizardBindingSource.DataMember = "protocol";
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataPropertyName = "wizardProtocol";
colType.DataSource = wizardBindingSource;
colType.DisplayMember = "protocolName";
colType.ValueMember = "idprotocols";
dataGridView.Columns.Insert(dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1, colType);
The most obvious thing that you are doing wrong is that you use the same binding source for both your datagridview and for your comboboxcolumn. If you look at the example you provided you'll notice that they create a second bindingsource productBindingSource.
So what you need to do is create a bindingsource (let's call it wizardProtocolBindingSource) which you then fill with the data from your protocols table. This becomes the datasource for your combobox column.
The key code looks something like this:
// You bind the datagridview just as before
// this dataset should have the idprotocols field which is your foreign key
// to the protocols table - you will probably want this to be hidden.
bindingSource = new BindingSource();
bindingSource.DataSource = dataSet;
bindingSource.DataMember = "pcap";
dataGridView.DataSource = bindingSource;
// hide the foreign key column
dataGridView.Columns["idProtocols"].Visible = false;
// here we populate your comboboxcolumn binding source
wizardProtocolBindingSource= new BindingSource();
// this dataset is from the protocols table
wizardProtocolBindingSource.DataSource = dataSet;
// Add the combobox column
DataGridViewComboBoxColumn colType = new DataGridViewComboBoxColumn();
colType.HeaderText = "Type";
colType.DropDownWidth = 90;
colType.Width = 90;
colType.DataSource = wizardProtocolBindingSource;
// The DataPropertyName refers to the foreign key column on the datagridview datasource
colType.DataPropertyName = "wizardProtocol";
// The display member is the name column in the column datasource
colType.DisplayMember = "protocolName";
// The value member is the primary key of the protols table
colType.ValueMember = "idprotocols";
// I usually just add the column but you can insert if you need a particular position
dataGridView.Columns.Add(colType);
The above should work for you, though not knowing the names of your dataset columns I had to guess a little.