I'm trying to make a windows application for Library Management.
I'm trying to bind the data generated by SQLQuery to comboBoxBranch, but its only showing --Select-- in the options. Is there anything wrong with following code?
private void Form1_Load(object sender, EventArgs e)
{
bindBranch();
}
private void bindBranch()
{
OleDbCommand SQLQuery = new OleDbCommand();
string sqlQueryString = "Select br_id from branch";
DataTable data = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
try
{
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
comboBoxBranch.DisplayMember = "br_id";
DataRow dr = data.NewRow();
dr[0] = "--Select--";
data.Rows.InsertAt(dr, 0);
comboBoxBranch.DataSource = data;
}
catch (Exception ex)
{
}
}
Is there anything else I need to add to some other pages to make this work?
You can bind data like this.
comboBoxBranch.DataSource = new BindingSource { DataSource = data };
comboBoxBranch.DisplayMember = "br_id";
comboBoxBranch.ValueMember = //> something else
Related
Why do I get the value System.Data.DataRowView? c# + sqlserver
I'm trying to add data to my table but ne system.Data.rowview and I don't know how to do it so that it doesn't come out
Why do I get the value System.Data.DataRowView? c# + sqlserver
This is where I load the items inside the Checklixbox
public void Cargar_Requerimientos(string Id_CR)
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT Id_CR, Requisitos, Id_RS FROM Requerimientos WHERE Id_CR =#Id_CR ", cn);
cmd.Parameters.AddWithValue("Id_CR", Id_CR);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cn.Close();
//DataRow dr = dt.NewRow();
//dr["Requisitos"] = "Seleciona un Requisitos";
// dt.Rows.InsertAt(dr, 0);
///////////////////////////////////////
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
checkedListBox1.DataSource = dt;
//bool state = true;
// for (int i = 0; i < checkedListBox1.Items.Count; i++)
// checkedListBox1.SetItemCheckState(i, (state ? CheckState.Checked : CheckState.Unchecked));
//dr = dt.NewRow();
enter code here
try
{
//checkedListBox1.DataSource = dt.Columns[0].ToString();
//dt.Columns[0].ToString();
//checkedListBox1.DataSource = dt.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here I upload the data from combobox1 to checklistbox1
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// checkedListBox1.Enabled = false;
{
if (comboBox1.SelectedItem.ToString() == null)
{
checkedListBox1.Enabled = true;
}
}
if (comboBox1.SelectedValue.ToString() != null)
{
string Id_CR = comboBox1.SelectedValue.ToString();
Cargar_Requerimientos(Id_CR);
}
Result:
The CheckListBox does not directly support a DataSource, which is why the property is hidden from intellisence.
Usually it is correct to set the DataSource after setting the DisplayMember and ValueMember properties, to avoid multiple refresh calls, but to avoid your issue, you have to set the DataSource property first:
checkedListBox1.DataSource = dt;
checkedListBox1.ValueMember = "Id_RS";
checkedListBox1.DisplayMember = "Requisitos";
I'm new to Asp.net and I'm trying to figure out how to update a value in a SqlDataSource programmatically. Here's my button click listener:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
The oldValue is false and the newValue is true so I am changing the value but it doesn't save to the database when I call AcceptChanges(). What am I doing wrong here? I've already spent hours on this. Thanks for your help!
I do not have what your DetailsSqlDataSource is, or what your database structure is like, but you would obviously need to write a few Save and Read methods.
If you did that, you would have something like this:
protected void ApproveLoanButton_Click(object sender, EventArgs e)
{
DataView dv = (DataView)DetailsSqlDataSource.Select(DataSourceSelectArguments.Empty);
dv.AllowEdit = true;
using (var dt = dv.ToTable())
{
var oldValue = dt.Rows[0]["IsApproved"].ToString();
if (-1 < SaveApproved((int)dt.Rows[0]["ID"], true))
{
dt.Rows[0]["IsApproved"] = true;
var newValue = dt.Rows[0]["IsApproved"].ToString();
dt.AcceptChanges();
DetailsSqlDataSource = GetTable();
GridView1.DataBind();
DetailsView1.DataBind();
}
}
}
You will need to modify these to work, but here is a sample:
private const string SQL_CONNECTION = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
private DataTable GetTable()
{
var table = new DataTable();
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("SELECT * FROM MyTable;", con))
{
table.Load(cmd.ExecuteReader());
}
}
return table;
}
private int SaveApproved(int rowID, bool approved)
{
using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
{
con.Open();
using (var cmd = new System.Data.SqlClient.SqlCommand("UPDATE MyTable SET IsApproved=#IsApproved WHERE ID=#ID;", con))
{
cmd.Parameters.Add("#IsApproved", SqlDbType.Bit).Value = approved;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = rowID;
return cmd.ExecuteNonQuery();
}
}
}
I have a table having 2 columns viz ID and DETAILS.Data in a table is like
id=01 details="pritam=123 sourav=263" like this
i am working on a windows for application ..when the application will run the output comes what i am going to tell.. 1.in my application one combobox is there.when the application will run all the id will be bind in a combobox from the table. 2.when user will choose any id suddenly the details column data will be shown in a datagrid view in a splitted format like this.
NAME KEY
PRITAM 123
SOURAV 263
in this data grid view user can delete ant row by selecting the and click on the below delete button. insert any row by clickng the add new row button at the end ,modify any existing data and finally click on the update button and all the data are going to be stored in that data base like in previous format.. for that i have written the code in c# like this..
namespace windows_csharpp
{
public partial class Form5 : Form
{
SqlConnection cc = new SqlConnection("Integrated Security=true;database=EDIXfer");
SqlDataAdapter da;
DataTable dt;
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
string sql="select EDIScheduleID from ETAProcessSchedule";
da= new SqlDataAdapter(sql, cc);
dt = new System.Data.DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
comboBox1.Items.Add(dt.Rows[x][0].ToString());
}
}
ArrayList ls = new ArrayList();
int ss = 0;
int ss1 = 0;
int ssp = 1;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql = "select * from ETAProcessSchedule where EDIScheduleID='" + comboBox1.SelectedItem.ToString() + "'";
SqlDataAdapter adp = new SqlDataAdapter(sql, cc);
DataTable dt = new System.Data.DataTable();
adp.Fill(dt);
string stp = dt.Rows[0][21].ToString();
string[] stp1 = stp.Split(' ');
List<Class1> lst = new List<Class1>();
ls.Clear();
for (int x = 0; x < stp1.Length; x++)
{
ls.Add(stp1[x].ToString());
}
for (int x = 0; x < ls.Count; x++)
{
string ssttt = ls[x].ToString();
string[] sssp = ssttt.Split('=');
for (int x1 = 1; x1 < sssp.Length; x1++)
{
ss = 0;
ss1 = ssp;
Class1 cs = new Class1()
{
Value = sssp[ss], Key= sssp[x1].ToString()
};
lst.Add(cs);
}
}
dataGridView1.DataSource = lst;
}
private void Update_Click(object sender, EventArgs e)
{
string value = null;
string keys = null;
string query = null;
string str = null;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
value = dataGridView1.Rows[i].Cells[0].Value.ToString();
keys = dataGridView1.Rows[i].Cells[1].Value.ToString();
string ss = value + '=' + keys;
str += ss + ' ';
}
query = "update ETAProcessSchedule set ProcParameters='"+str+"' where EDIScheduleID='"+comboBox1.SelectedItem.ToString()+"'";
da = new SqlDataAdapter(query, cc);
dt = new DataTable();
da.Fill(dt);
MessageBox.Show("Data Updated In Database Successfully");
}
and one class file is also there ..
class Class1
{
public string Value { get; set; }
public string Key { get; set; }
}
kindly help me in delete the selected row ,add the new row and update the all data in database like in previous format..
I think you already have working approach. If I understand right you need only two functions:
- Load Schedule details in the DataGridView (one key-value pair per row)
- Save edited/added/deleted key-value pairs to the database
Be sure next properties of DataGridView set to true:
this.YourDataGridView.AllowUserToAddRows = true;
this.YourDataGridView.AllowUserToDeleteRows = true;
And of course columns must be editable
In the methods was used const variables which was created in your Form (Form1)
private const string DETAILSDELIMITER = ' ';
private const string NAMEKEYDELIMITER = '=';
Method for loading schedule details in the DataGridView
//Use SqlParameters in the query,
//if not your application vulnerable for sql injection
private void LoadScheduleDetails(string scheduleID)
{
//You working only with one column, do not use '*' in SELECT statement if not nessesary
string query = "SELECT EDIScheduleID, ProcParameters FROM ETAProcessSchedule WHERE EDIScheduleID = #ScheduleID";
DataTable details = new DataTable();
//Get data from database
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using(SqlCommand detailsCommand = new SqlCommand(query, yourConnection))
{
//Adding parameter
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
detailsCommand.Parameters.Add(id);
using (SqlDataAdapter yourAdapter = new SqlDataAdapter(detailsCommand ))
{
yourAdapter.Fill(details);
}
}
}
this.YourDataGridView.Rows.Clear();
if (details.Rows.Count > 0)
{
DataRow temp = details.Rows[0];
//get column by name.
string[] pairs = temp.Field<String>("ProcParameters").Split(Form1.DETAILSDELIMITER);
//Adding rows manually without DataSource
foreach(string pair in pairs)
{
this.YourDataGridView.Rows.Add(pair.Split(Form1.NAMEKEYDELIMITER));
}
}
}
Method for saving data
I think better if you create columns already in the designer
Then you can access columns by it's name without hardcoding indexes
private void SaveDetails(string scheduleID)
{
StringBuilder details = new StringBuilder();
foreach(DataGridViewRow dgvr in this.YourDataGridView.Rows)
{
string name = dgvr.Cells[this.dgvColumn_Name.Name].Value.ToString();
string key = dgvr.Cells[this.dgvColumn_Key.Name].Value.ToString();
//Here you can check if values are ok(not empty or something else)
//Create pair
details.Append(Form1.DETAILSDELIMITER);
details.Append(name);
details.Append(Form1.NAMEKEYDELIMITER);
details.Append(key);
}
//remove first space character
if (details.Length > 0)
details.Remove(0, 1);
//Save data to database
string query = "UPDATE ETAProcessSchedule SET ProcParameters=#Details WHERE EDIScheduleID=#ScheduleID";
using (SqlConnection yourConnection = new SqlConnection(_YourConnectionString))
{
using (SqlCommand saveCommand = new SqlCommand(query, yourConnection))
{
//Adding parameters
SqlParameter id = new SqlParameter { ParameterName = "#ScheduleID", SqlDbType = SqlDbType.NVarChar, Value = scheduleID };
SqlParameter procParams = new SqlParameter { ParameterName = "#Details", SqlDbType = SqlDbType.NVarChar, Value = details.ToString() };
saveCommand.Parameters.Add(id);
saveCommand.Parameters.Add(procParams);
saveCommand.ExecuteNonQuery();
MessageBox.Show("Data Updated In Database Successfully");
}
}
}
Then use LoadScheduleDetails in the comboBox1_SelectedIndexChanged eventhandler
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.LoadScheduleDetails(scheduleID);
}
}
After data loaded, user can change it, add rows, delete rows
When user pressed "Update" button then use SaveDetails method,
where we collect data from all rows and update database with it
private void Update_Click(object sender, EventArgs e)
{
string scheduleID = comboBox1.SelectedItem.ToString();
if(String.IsNullOrEmpty(scheduleID) == false)
{
this.SaveDetails(scheduleID);
}
}
On your form load bind data:-
EDIT : -
private void Form5_Load(object sender, EventArgs e)
{
comboBox1.DataSource = loadddltable();
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
}
public DataTable loadddl()
{
OleDbDataReader obj = null;
DataTable dt = new DataTable();
try
{
obj_dbconnection.CommandText = "Select * from TableName";
obj = obj_dbconnection.ExecuteReader();
if (obj != null)
{
if (obj.HasRows)
{
dt.Load(obj);
}
}
}
catch (Exception)
{
}
finally
{
if (obj != null)
{
obj.Close();
obj_dbconnection.Close();
}
}
return dt;
}
/*Code for Execute Reader*/
public OleDbDataReader ExecuteReader()
{
OleDbDataReader dr = null;
try
{
Open();
dr = cmd.ExecuteReader();
}
catch(Exception)
{ }
return dr;
}
/*Code for binding grid data*/
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource= getDataForSelectedId(comboBox1.SelectedValue);
}
And then insert,edit,delete buttons as template fields to dataGridView and use dataGridView1_CellClick event to insert edit delete
i create a winform application with a listbox datasource that come from ms access database. the problem is when i click the Update button the listbox is not getting update. example i change the "ITEM1" to ITEM2", its just not working but the database do because i execute a command that will update the database. i need to reload(re-open) my application then on that time i will see my modification. how do i update the listbox? i've read something about this problem before but i dont understand about it clearly..i wish someone could help me out..
private BindingList<PRODUCTLIST> _productlist;
public Form1()
{
InitializeComponent();
}
public class PRODUCTLIST
{
public string ID { get; set; }
public string ITEM { get; set; }
public string ITEM_DESC { get; set; }
}
private static OleDbConnection GetConnection()
{
OleDbConnection mdbConn = new OleDbConnection();
try
{
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=shop.mdb;Jet OLEDB:Database Password=xxxxx;";
mdbConn = new OleDbConnection(connectionString);
mdbConn.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return mdbConn;
}
private void Form1_Load(object sender, EventArgs e)
{
// make ID textbox un editable
textBoxID.Enabled = false;
_productlist = new BindingList<PRODUCTLIST>();
string strSQL = "SELECT * FROM Item ORDER BY ITEM";
OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, GetConnection());
DataSet dtSet = new DataSet();
myCmd.Fill(dtSet, "Item");
DataTable dTable = dtSet.Tables[0];
foreach (DataRow dtRow in dTable.Rows)
{
_productlist.Add(new PRODUCTLIST() { ID = dtRow["ID"].ToString(), ITEM = dtRow["ITEM"].ToString(), ITEM_DESC = dtRow["ITEM_DESC"].ToString() });
}
listBox1.DisplayMember = "ITEM";
listBox1.DataSource = _productlist;
//listBox1.DataBindings = _productlist;
listBox1.ValueMember = "ID";
// set the textbox binding and DataSourceUpdateMode to Never because i have other button to add the new item
textBoxID.DataBindings.Add("Text", _productlist, "ID", false, DataSourceUpdateMode.Never);
textBoxITEM.DataBindings.Add("Text", _productlist, "ITEM", false, DataSourceUpdateMode.Never);
textBoxITEMDESC.DataBindings.Add("Text", _productlist, "ITEM_DESC", false, DataSourceUpdateMode.Never);
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
// update data on database
OleDbCommand cmd = new OleDbCommand("UPDATE Item SET ITEM = #ITEM, ITEM_DESC = #ITEM_DESC WHERE ID = #ID", GetConnection());
cmd.Parameters.AddWithValue("#ITEM", textBoxITEM.Text);
cmd.Parameters.AddWithValue("#ITEM_DESC", textBoxITEMDESC.Text);
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(textBoxID.Text));
cmd.ExecuteNonQuery();
// make the listbox datasource update
//listBox1.Refresh();
//listBox1.DataSource = null;
//listBox1.DataSource = _productlist;
//_productlist = new BindingList<PRODUCTLIST>();
//string strSQL = "SELECT * FROM Item ORDER BY ITEM";
//OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, GetConnection());
//DataSet dtSet = new DataSet();
//myCmd.Fill(dtSet, "Item");
//DataTable dTable = dtSet.Tables[0];
//foreach (DataRow dtRow in dTable.Rows)
//{
// _productlist.Add(new PRODUCTLIST() { ID = dtRow["ID"].ToString(), ITEM = dtRow["ITEM"].ToString(), ITEM_DESC = dtRow["ITEM_DESC"].ToString() });
//}
//listBox1.DisplayMember = "ITEM";
//listBox1.DataSource = _productlist;
////listBox1.DataBindings = _productlist;
//listBox1.ValueMember = "ID";
}
The way you are doing it you need to clear and repopulate your list box.
You should extract that code as a method from the FormLoad event handler and call it after you run the update query.
It's hard to tell which way you want to go. Based on what you are asking.
What you should be doing is making your products data table a private property. Creating and open it up and bind to the list box.
Then your update function should be changing the datatable. Then you'd see the changes in your list box. The thing to appreciate though is until you flush the changes (ApplyChanges method) you have made to the datatable back to the database server all you've done is change a local copy of the data.
That can be good and bad. Depends on what you want to do with multiple users updating products at the same time.
So you've got datatable with a local copy and shown it.
Then you've updated the table you copied, and now your copy is out of step.
Exactly the same problem you would have, if you ran up another copy of your app and changed one of the records you'd already shown in the first one.
I am making windows application and am stuck at one place.
My problem is that i want to display record in a DataGridView by selecting a ComboBox item but I do not understand the proper way to do it. Please help me in overcome this problem.
private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);
try
{
con.Open();
//this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
//above line show error for connection to database
da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "stud_no";
comboBox1.ValueMember = "stud_no";
comboBox1.DataSource = dt;
comboBox1.SelectedIndex = -1;
comboBox1_SelectedIndexChanged(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{ con.Close(); }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
//above line show error for connection to database
}
i have tried above code but its not working there error like login fail to user
cmd = new SqlCommand("SELECT stud_no FROM stud", con);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
Combobox1.DataSource = dt;
Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;
rebind the DataGrid at each SelectedItemIndex change event of Combo Box by the data you want to bind.
private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
{
if (combo_floor.Text != "")
{
DataSet ds = new DataSet();
string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
ds = c.select_query(sql);
dataGridView1.DataSource = ds.Tables["a"];
combo_floor.Text = "";
}
else
{
showdata();
//showdata()is made for show all data from the given table name
}
}
//connection is in different class so please dont mind