I have been working on asp.net. I have a registration form with grid view.
The grid view contains the id of dropdownlist(ddl).
when i select the grid view ,all values have to be shown in appropriate fields in registration form.
For ddl, from the ddl id value in grid view ,appropriate dropdown list text is shown in dropdownlist.
THE PROBLEM COMES HERE, dropdown list showing only the appropriate value and AGAIN IT CANNOT BE CLICKED AND POPULATED FOR UPDATE BUTTON
enter image description here.
cmd.CommandText = "SELECT * FROM COMPANY WHERE COMPANYID='" + dbCompany + "'";
txtTextBox1.Text = newcmpid;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
ddlCompanyName.DataBind();
HOW TO POPULATE THE DROPDOWNLIST WITH ALL ELEMENTS BY THE SAME TIME HIGHLIGHTING THE APPROPRIATE VALUE
To achive selection just use:
ddlCompanyName.Items.FindByValue(dbCompany).Selected = true;
But You should also notice that you SQL query is dangorous. It allows to create SQL inject attack. Instead of concatenating it you should SQL params.
So the full code could be like this:
cmd.CommandText = "SELECT * FROM COMPANY WHERE COMPANYID=#ID;";
cmd.Parameters.Add("#ID", SqlDbType.Int);
cmd.Parameters["#ID"].Value = dbCompany;
txtTextBox1.Text = newcmpid;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
ddlCompanyName.DataBind();
ddlCompanyName.Items.FindByValue(dbCompany).Selected = true;
Related
I have a dropdown list. I am getting data from oracle data base as a dataset I want to fill the dropdown list with dataset values(data text field and data value field). Data coming from the database as normal but I cant bind the values with my drop down list. "ds" is the dataset.
ddlDepartment.DataValueField = ds. Tables[0].Rows[0]["DEPARTMENT"].ToString();
ddlDepartment.DataTextField = ds. Tables[0].Rows[0]["DEPARTMENT_NAME"].ToString();
I think you might be grasping this wrong.
The dropdown combo has a simple setting that allows you to "set" WHAT values from the datasource will be used from the data table you "feed" the drop down list.
So, you can have this markup:
<asp:DropDownList ID="DropDownList1" runat="server"
Height="26px" Width="207px"
DataValueField="ID"
DataTextField="HotelName"
>
</asp:DropDownList>
So, you can set the two columns used - they are NOT for feeding data to the dropodown.
You can also set the above two columns in code - but LITTLE need exists to do that.
eg:
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "HotelName";
ONCE you set the above, you are now free to query the database, load up say a datatalbe, and then assign that "table" to the Dropdown list.
You do it this way:
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL = "SELECT ID,HotelName, City FROM tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
DropDownList1.DataSource = rstData;
DropDownList1.DataBind();
// add one blank row selection.
DropDownList1.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
So, note how the data table has 3 columns, but WHICH of the 3 do you want to use fo for the dropdown? You have two columns - typical the "ID" or "PK" value, and then the 2nd column is a text description.
Now, I am using the SqlProvider (for sql server). You have to replace SqlCommand with the OracleSQLcommand and also the connection. But the data table, and code that fills the dropdown list reamins the same as per above - regardless of what data provider you are using.
So those two settings (DataValueField, DataTextField) are NOT to be feed data, but are ONLY to set which columns to use from the data table. My example had 3 columns, but there could be 20 columns in that table - so those two settings determine which two columns to use. And often you might have a simple drop down to select a color or some such - and thus you ONLY need one column. In that case, set both Value/Text field to the one same column.
I was able to fill the dataset as follows at the page load
`private void filldepartment()
{
UserClass obj = new UserClass();
DataSet ds2 = new DataSet();
ds2.Merge(obj.departments());
ddlDepartment.DataSource = ds2.Tables[0];
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataBind();
}`
and then find the values as follows
ddlDepartment.DataSource = ds;
ddlDepartment.DataBind();
Adjusted version of your code, removing unnecessary operations:
private void FillDepartmentDropDown()
{
UserClass obj = new UserClass();
var dt = obj.GetDepartments();
ddlDepartment.DataTextField = "DEPARTMENT_NAME";
ddlDepartment.DataValueField = "DEPARTMENT_ID";
ddlDepartment.DataSource = dt;
ddlDepartment.DataBind();
}
And then GetDepartments might look like:
public DataTable GetDepartments(){
using var da = new OracleDataAdapter(
"SELECT department_id, department_name FROM departments ORDER BY NLSSORT(department_name, 'NLS_SORT=GENERIC_M')",
_connstr
);
var dt = new DataTable();
da.Fill(dt);
}
I have two forms, in one I fill DataGridView with some rows, each row has two comboboxes.
I am able to get both value and formatted value from these cells, however when I try to copy all of this data into the next DataGridView that is in different form, I am unable to tell him which item from the ComboBox should be marked as selected.
When I was looking around I found these lines of code (unfortunately they were from 6+ years ago)
dataGridView.Rows[index].Cells[3].Value = ImageFormat.Items[1];
(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = ImageFormat.Items[0];
DataGridViewComboBoxCell comboboxFormat = (DataGridViewComboBoxCell)(dataGridView.Rows[index].Cells[3]);
comboboxFormat.Value = ImageFormat.Items[0];
(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = (dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Items[0];
Unfortunately none of these worked and most if not all threw "DataGridViewComboBoxCell value is not valid" exception
Maybe it's worth to mention that the possible items are binded from database like so:
string stm = "SELECT * FROM colours";
using var cmd = new SQLiteCommand(stm, MainWin.con);
SQLiteDataAdapter rdr = new SQLiteDataAdapter(cmd);
DataTable dataTableColour = new DataTable();
rdr.Fill(dataTableColour);
stm = "SELECT * FROM formats";
using var cmdd = new SQLiteCommand(stm, MainWin.con);
SQLiteDataAdapter reader = new SQLiteDataAdapter(cmdd);
DataTable dataTableFormat = new DataTable();
reader.Fill(dataTableFormat);
ImageFormat.ValueMember = "id";
ImageFormat.DisplayMember = "name";
ImageFormat.DataSource = dataTableFormat;
ColourImage.ValueMember = "id";
ColourImage.DisplayMember = "name";
ColourImage.DataSource = dataTableColour;
Your datagridview should be bound to some datatable (let's say ImageFiles). Set ColourImage/ImageFormat combo's .DataPropertyName property to be the name of the column in the [ImageFiles] datatable that the combo should edit. Don't try to interact with the DGVCombo directly; just interact with the datatable to which the grid is bound
I am writing a small application in C# using windows forms. I have a combo box that I am populating by querying a database for column names to use as the values inside the combo box. My code currently can get the values just fine, however whenever I click on the combo box it removes any text and just displays a blank 'selected option'. I have tried multiple things to correct this (changed the database field from char to varchar), tried binding to a different dataset etc. but nothing has worked. Ive also looked at other posts on this such as
C# comboBox databinding - nothing happens, then it goes back to blank
Below is my code, and I believe I am doing the displaymember/valuemember part wrong however I do not understand what it is that is wrong. The column name in the database is Reason and it consists of 3 values.
Any help is appreciated.
String ConnString = ConfigurationManager.ConnectionStrings["Portal1"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
SqlCommand sc = new SqlCommand("select [Reason] from tblReasons", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Reason", typeof(string));
dt.Load(reader);
cboxReason.ValueMember = "Reason";
cboxReason.DisplayMember = "Reason";
cboxReason.DataSource = dt;
conn.Close();
Your code looks OK. I would not add the column, that should happen automatically. Here is my sample code that works:
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
var reader = new SqlCommand("select ID from Users", conn).ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = dt;
conn.Close();
Note: This populates with the list of values in the column. For the list of column names, I would suggest changing your query to return a list of columns for the table (DB specific query) OR look at the DataTable.Columns collection for the column names.
Did you try the answer from C# - Fill a combo box with a DataTable
cboxReason.BindingContext = this.BindingContext;
I have Gridview (gridview1), some TextEdits in the Form and add some Data's to few rows and i stored the gridview1 Data's and textedits to Access Database. In another form i Bind some column to gridview1 and TextEdits to new Gridview (gridview2). Now if i click edit button on any row in the gridview2, I want to get the Data's from Access Database and shown in 1st Form gridview1 and textedits fill automatically recording to Focused Row cell unique value.
Using this code i get value to TextEdits Fields
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb");
OleDbCommand da = new OleDbCommand("select * from invoice_top where invoice_number=" + textEdit5.Text, con);
con.Open();
OleDbDataReader reader = da.ExecuteReader();
while (reader.Read())
{
textEdit12.Text = reader.GetValue(1).ToString();
textEdit13.Text = reader.GetValue(2).ToString();
textEdit4.Text = reader.GetString(3);
dateEdit1.Text = reader.GetValue(8).ToString();
textEdit1.Text = reader.GetValue(5).ToString();
textEdit2.Text = reader.GetValue(6).ToString();
textEdit3.Text = reader.GetValue(7).ToString();
checkEdit1.Checked = reader.GetBoolean(4);
}
con.Close();
I also want to fill gridview Data's ? I tried this bus its not working
gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[2], reader1.GetString(2));
How to set Access Database values to grdiview ?? Please Help me ?
Thanks in Advance.
I think you need to read a tutorial on Data Binding.
The GridControl can be bound to a data source which implements IList<>, IBindingList<> or IQueryable<> simply by setting the GridControl.DataSource property. There is no need to loop through your recordset and set the value for each row/cell individually. Additionally, I would suggest you Data Bind your TextEdit controls (to the EditValue property, NOT the Text property) rather than manually setting them like you are doing above.
This code is VB.NET but the ideea is the same in C#
Dim SIRCON as string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb"
Using con As New OleDbConnection(SIRCON)
con.Open()
Dim strSQL As String = "select * from invoice_top where invoice_number=" + textEdit5.Text
dim dt as new datatable
dt.Load(New OleDbCommand(strSQL, conexiune).ExecuteReader())
conexiune.Close()
GridControl1.datasource = dt
GridControl1.ForceInitialise
End Using
I have an application,which is not able to fetch data from the database for this specific form, while other forms are working fine.
I am using this form to fetch data from database and then display that data onto labels on an another form.
The code for fetching data is:
string PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno, PAge, Amount;
SqlDataAdapter a = new SqlDataAdapter("Select bills.BillNo,bills.PName,bills.DName,bills.PAge,bills.PSex,bills.PPhoneNo,bills.PAddress,bills.Treatment,bills.Amount,bills.Teethno,addpro.Medicines from bills,addpro where bills.BillNo=" + bno, Program.con);
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[3]);
Amount = Convert.ToString(t.Rows[8]);
PName = Convert.ToString(t.Rows[1]);
DName = Convert.ToString(t.Rows[2]);
Psex = Convert.ToString(t.Rows[4]);
PPhoneNo = Convert.ToString(t.Rows[5]);
PAddress = Convert.ToString(t.Rows[6]);
Treatment = Convert.ToString(t.Rows[7]);
Teethno = Convert.ToString(t.Rows[9]);
frmPrint sa=new frmPrint();
sa.start(bno, PAge, Amount, PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno);
when i try to load the next form which displays the data from this DataTable on labels it gives the following error:-
There is no row at position 3.
Your're using Row and you want to be using Column:
foreach(DataRow row in t.Rows)
{
PAge = row["PAge"].ToString();
Amount = row["Amount"].ToString();
PName = row["PName"].ToString();
DName = row["DName"].ToString();
Psex = row["PSex"].ToString();
PPhoneNo = row["PPhoneNo"].ToString();
PAddress = row["PAddress"].ToString();
Treatment = row["Treatment"].ToString();
Teethno = row["Teethno"].ToString();
}
Instead of using the number to identify the column, use the name. If the order of the query was to change for any reason, this would not have an impact on your code. If you used the Ordinal number, then you would need to change your row[n] code too since the order would have changed.
You are accessing different rows for each field.
You should access the first row and then different columns:
t.Rows[0].Columns[0]
t.Rows[0].Columns[1]
t.Rows[0].Columns[2]
t.Rows[0].Columns[3]
...
Seems like you need to use [Columns]
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[0]["ColumnsName"]);
// and so on