show data in Listbox c# from sql - c#

I have this code to show data from SQL to listbox in c#
public DataTable get_mada_listbox()
{
DAL.DATAACSESSLAYER dal = new DAL.DATAACSESSLAYER();
dal.open();
DataTable dt = new DataTable();
dt = dal.selectData("get_mada_listbox", null);
dal.close();
return dt;
}
When I call the function:
BL.cls_product prd = new BL.cls_product();
listBox1.DataSource = prd.get_mada_listbox();
The listbox should show
system.data.data row view.
How can I solve it?
i solve my problem by add
listBox1.DisplayMember = "mada_name";
next this
listBox1.DataSource = prd.get_mada_listbox();
thx

This should be your method:
void get_mada_listbox()
{
var connection = ConfigurationManager.ConnectionStrings[name].ConnectionString;
using (SqlConnection connsql = new SqlConnection(connString))
{
connsql.Open();
// Sql Adapter
using (SqlDataAdapter sqlAdapter = new SqlDataAdapter("SELECT * FROM DataTable", connection))
{
// fill a data table
var data_table = new DataTable();
sqlAdapter.Fill(t);
// Bind the table to the list box
listBox1.DisplayMember = "mada_name";
listBox1.ValueMember = "mada_value";
listBox1.DataSource = data_table;
}
}
}

Related

combobox value not showing in C#

I get problem while loading Combobox value from database. I am using SQLite Database. It only show a single value in Combobox but in my database there is multiple value. So how can i do this.
This is my Code:
Class DatabaseHandler it has two methods which Execute Query and other methods return DataTable object:-
public int ExecuteSql(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
return command.ExecuteNonQuery();
}
public DataTable GetDataTable(String Query)
{
SQLiteCommand command = new SQLiteCommand(Query, Connection);
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(command);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
return dataTable;
}
This is Category Class and this is piece of code where i got a problem:-
private void CategoryName()
{
try
{
String Query = "Select CategoryName from CategoryTable;";
databaseHandler.ExecuteSql(Query);
DataTable dataTable = databaseHandler.GetDataTable(Query);
ProductType.DataSource = dataTable;
ProductType.DisplayMember = "CategoryName";
}
catch (Exception CatID)
{
Console.WriteLine(CatID.StackTrace);
}
}
I think you are assigning a DisplayMember but not ValueMember. Please assign the DisplayValue along with ValueMember.
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

how to update GridView row at once in sql database

I have DLL class to call the table
public DataTable GetTemTableValue(string TableName)
{
SqlConnection conn = new SqlConnection(sConnectionString);
conn.Open();
string query = "select * from " + TableName + "";
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
DataTable ds = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
return ds;
}
and i am binding the table to grid view
private void LoadData()
{
clsDataAccess objDAL = new clsDataAccess();
DataTable DS = new DataTable();
string objBLL = DDLTemTableList.SelectedValue.ToString();
DS = objDAL.GetTemTableValue(objBLL);
if (DS != null && DS.Rows.Count != 0)
{
lblNoRecord.Visible = false;
foreach (DataColumn col in DS.Columns)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
//Add the newly created bound field to the GridView.
GVDataEntry.Columns.Add(bfield);
}
GVDataEntry.DataSource = DS;
GVDataEntry.DataBind();
GVDataEntry.Visible = true;
}
else
{
lblNoRecord.Visible = true;
GVDataEntry.DataSource = null;
GVDataEntry.DataBind();
//GVDataEntry.EmptyDataText = "No recorddata found";
}
so Table is loading to Grid View. every time when i change the tables in dropdownbox and press search button columns will change dynamically so how can i update data in Grid view through using RowEditing,RowUpdating function and i need to store the date in database?

SQLite - storing the column names of a table in a list of strings

I don't know how to store the column names from a SQLite table into a list of strings.
The following code fills a dataGridView with the column names (amongst other things):
string sDatabasePath = DBPath();
SQLiteConnectionStringBuilder datasource = new SQLiteConnectionStringBuilder();
datasource.Add("Data Source", sDatabasePath);
datasource.Add("Version", "3");
datasource.Add("New", "False");
datasource.Add("Compress", "True");
using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString))
{
connection.Open(); //opens connection
SQLiteCommand getColumnNames = new SQLiteCommand("PRAGMA table_info('myTable');", connection);
SQLiteDataAdapter myAdapter = new SQLiteDataAdapter(getColumnNames);
DataSet myDataSet = new DataSet();
//myAdapter.Fill(myDataSet, "name");
this.dataGridView1.DataSource = myDataSet;
this.dataGridView1.DataMember = "name";
connection.Close();
}
If you are looking to bind your query to a list and not a DataGridView, then you should use a data reader and not a data set e.g.
using (SQLiteConnection connection = new SQLiteConnection(datasource.ConnectionString))
using (SQLiteCommand cmd = new SQLiteCommand("PRAGMA table_info('myTable');"))
{
connection.Open(); //opens connection
var tableNames = new List<string>();
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
tableNames.Add(reader.GetString(0)); // read 'name' column
}
}
return tableNames;
}
DataTable dtb = new DataTable();
myAdapter.Fill(dtb);
string[] names = new string[dtb.Rows.Count];
for (int i = 0; i < dtb.Rows.Count; i++)
{
DataRow row = dtb.Rows[i];
names[i] = row[0].ToString();
}

i just try to search the result by the name of school.but the grid view didnt show any thing

this is my code...i just try to search the result by the name of school.but the grid view didnt show any thing.my code is
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
gvResult.DataSource = dtbl;
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
}
protected void Button1_Click(object sender, EventArgs e)
{
gridfill();
}
public DataTable markViewAll()
{
DataTable dtbl = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewAll", sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.Fill(dtbl);
return dtbl;
}
public DataTable markViewBySchool(string viewBySchool)
{
DataTable dtbClass = new DataTable();
SqlDataAdapter sqlda = new SqlDataAdapter("markViewBySchool",sqlcon);
sqlda.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlda.SelectCommand.Parameters.Add("#schoolName", SqlDbType.VarChar).Value = viewBySchool;
sqlda.Fill(dtbClass);
return dtbClass;
}
change as below, there are few problems in your code, why two times databinding to same gridview? even you data bind two times it only show what you set at the last time. i have removed few lines of code and you forgot to call gvResult.DataBind() as well
public void gridfill()
{
markSp spMark = new markSp();
gvResult.DataSource = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataBind();
}
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll();
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.Databind(); // You forgot DataBind()
}
Since you have tagged with ASP.Net, you need to call DataBind
gvResult.DataBind();
So your method would be:
public void gridfill()
{
markSp spMark = new markSp();
DataTable dtbl = new DataTable();
dtbl = spMark.markViewAll(); //you are not using this anywhere
gvResult.DataSource = dtbl; // so you can get rid of these two lines
dtbl = spMark.markViewBySchool(txtSchoolName.Text);
gvResult.DataSource = dtbl;
gvResult.DataBind(); // This is missing
}
You should see: ASP.NET data binding overview

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}

Categories