I need to add All as a selectable choice to the top of a combobox on winform. I have tried both of the codes below, which one does not throw an error but the value is not added:
public void GetData()
{
using (SqlConnection conn = new SqlConnection(SqlConnection))
{
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
cboemployees.Items.Insert(0, "All");
cboemployees.DisplayMember = "empname";
cboemployees.DataSource = ds.Tables["Test"];
}
}
Now this syntax throws an error of
error column 'empname' does not belong to table
public void GetData()
{
using (SqlConnection conn = new SqlConnection(SqlConnection))
{
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
DataRow row = dt.NewRow();
row["empname"] = "All";
dt.Rows.InsertAt(row, -1);
cboemployees.DataSource = dt;
}
}
What is the proper way of adding a selectable item to the top of a bound combobox?
Add the row to your table instead.
SqlDataAdapter da = new SqlDataAdapter("select [empname] from [Testdb].[dbo].[Test] order by [empname] Asc", conn);
conn.Open();
da.Fill(ds, "Test");
// Add the row for All
var allRow = ds.Tables["Test"].NewRow();
allRow[0] = "All";
ds.Tables["Test"].Rows.InsertAt(allRow, 0);
cboemployees.DisplayMember = "empname";
cboemployees.DataSource = ds.Tables["Test"];
Related
Hi i have combobox with Table names. I would like to display selected table on button click. How to do it? This is code of my combobox
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM sys.tables", Con);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Load(rdr);
wczytywanie.ValueMember = "name";
wczytywanie.DataSource = dt;
Con.Close();
now i would like to display these tables in dataGridView after button click.This is not working.
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT * from sys.tables where name=#name", Con);
cmd.Parameters.Add("name", wczytywanie.SelectedValue.ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Dane.DataSource = dt;
Con.Close();
try adding DisplayMember and assign value "name"
wczytywanie.ValueMember = "name";
wczytywanie.DisplayMember = "name";
This might do
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn);
DataSet DS = new DataSet();
adapter.Fill(DS);
advancedDataGridView1.DataSource = DS.Tables[0];
conn.Close();
And to change the column name your sql be like columnname as 'your preferred column name'
SELECT principal_id as 'Principal ID' from sys.tables where name=#name"
Following code does not delete a row from dataset and dont update the database....
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select *from RegisterInfoB", con);
ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"] == "praveen")
{
dr.Delete();
}
}
ds.Tables[0].AcceptChanges();
How to resolve this problem...How do I update my sql server database...by deleting a row from dataset..
I hope this will work for you:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
foreach (DataRow dr in ds.Tables[0].Rows)
{
if (dr["FirstName"].ToString().Trim() == "praveen")
{
dr.Delete();
}
}
adpt.Update(ds);
Two Changes
1st: if (dr["FirstName"].ToString().Trim() == "praveen") trimming the blank spaces in your db's FirstName Field.
2nd : use adpt.Update(ds); to update your DB.
Another Way to doing it:
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection();
con.ConnectionString = cs;
string firstName= "praveen"; // this data will get from calling method
SqlDataAdapter adpt = new SqlDataAdapter("Select * from RegisterInfoB", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "RegisterTable");
string deleteQuery = string.Format("Delete from RegisterInfoB where FirstName = '{0}'", firstName);
SqlCommand cmd = new SqlCommand(deleteQuery, con);
adpt.DeleteCommand = cmd;
con.Open();
adpt.DeleteCommand.ExecuteNonQuery();
con.Close();
Similary, you can write query for UpdateCommand and InsertCommand to perform Update and Insert Respectively.
Find rows based on specific column value and delete:
DataRow[] foundRows;
foundRows = ds.Tables["RegisterTable"].Select("FirstName = 'praveen'");
foundRows.Delete();
EDIT: Adding a DeleteCommand to the data adapter (based on example from MSDN)
Note: Need an Id field here instead of FirstName, but I don't know your table structure for RegisterInfoB. Otherwise, we delete everyone named "praveen".
// Create the DeleteCommand.
command = new SqlCommand("DELETE FROM RegisterInfoB WHERE FirstName = #FirstName", con);
// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("#FirstName", SqlDbType.NChar, 25, "FirstName");
parameter.SourceVersion = DataRowVersion.Original;
// Assign the DeleteCommand to the adapter
adpt.DeleteCommand = command;
To update a database with a dataset using a data adapter:
try
{
adpt.Update(ds.Tables["RegisterTable"]);
}
catch (Exception e)
{
// Error during Update, add code to locate error, reconcile
// and try to update again.
}
Sources: https://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.120).aspx
https://msdn.microsoft.com/en-us/library/y06xa2h1(v=vs.120).aspx
hope that resolve the problem,
Try it:
var connectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
var selectQuery = "Select * from RegisterInfoB";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand selectCommand = new SqlCommand(selectQuery, connection);
SqlDataAdapter adapter = new SqlDataAdapter(selectCommand);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
DataSet dataSet = new DataSet();
// you can use the builder to generate the DeleteCommand
adapter.DeleteCommand = builder.GetDeleteCommand();
// or
// adapter.DeleteCommand = new SqlCommand("DELETE FROM RegisterInfoB WHERE Id= #Id", connection);
adapter.Fill(dataSet, "RegisterInfoB");
// you can use the foreach loop
foreach (DataRow current in dataSet.Tables["RegisterInfoB"].Rows)
{
if (current["FirstName"].ToString().ToLower() == "praveen")
{
current.Delete();
}
}
// or the linq expression
// dataSet.Tables["RegisterInfoB"]
// .AsEnumerable()
// .Where(dr => dr["FirstName"].ToString().ToLower().Trim() == "praveen")
// .ToList()
// .ForEach((dr)=> dr.Delete());
var result = adapter.Update(dataSet.Tables["RegisterInfoB"]);
also you can add some events and put a breakpoint to see if the state is changing or if there is an error that prevent changes on the source:
dataSet.Tables["RegisterInfoB"].RowDeleted += (s, e) =>
{
var r = e.Row.RowState;
};
dataSet.Tables["RegisterInfoB"].RowDeleting += (s, e) =>
{
var r = e.Row.RowState;
};
From the title above, Im making a windows form in c# where in 2 of my checkedlistbox should populate the values from 2 tables in the database. However, when I tried to run the code, I always get this exception: "Cannot bind to the new value member".
below is my code. if you could find any errors/suggestions, feel free to comment. It would be a big help. thanks!
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM data_condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
dt.TableName = "data_condition";
da.Fill(dt);
checkedListBox1.DataSource = dt;
checkedListBox1.DisplayMember = "conname";
checkedListBox1.ValueMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
NpgsqlCommand cmd2 = new NpgsqlCommand("SELECT * FROM data_allergy", conn);
cmd2.CommandType = CommandType.Text;
NpgsqlDataAdapter da2 = new NpgsqlDataAdapter(cmd2);
dt2.TableName = "data_allergy";
da2.Fill(dt2);
checkedListBox2.DataSource = dt2;
checkedListBox2.DisplayMember = "allergyname";
checkedListBox2.ValueMember = "allerygid";
string[] allergy = dt2.Rows[0]["allergyname"].ToString().Split(',');
I have created a form in asp.net,where i have some textbox, in which I have taken some input which is stored in the database. I have created another page where I have taken the same number of label as the textbox.
I want to show the data in the labels that I last entered.
How can i do that?
Code:
string cs = ConfigurationManager.ConnectionStrings["TrishanConnection"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 coil_id FROM CoilDetails ORDER BY coil_id DESC", con);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
LabeCoilid.Text = ds.ToString();
LabeCoilid.DataBind();
con.Close();
Try instead of
LabeCoilid.Text = ds.ToString();
this
LabeCoilid.Text = ds.Tables[0].Rows[0][0].ToString();
LabeCoilid.Text = ds.Tables[0].Rows[0]["coil_id"].ToString();
You don't need to call DataBind()
string cs = ConfigurationManager.ConnectionStrings["TrishanConnection"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 coil_id FROM CoilDetails ORDER BY coil_id DESC", con))
{
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(ds);
dt=ds.Table[0]
}
}
LabeCoilid.Text = dt.Rows[0][0].ToString();
LabeCoilid.DataBind();
con.Close();
You can change the rows and columns by changing dt,Rows[4][8]
It's my first time to implement INNER JOIN query in SQL.NET and C#.NET. I get this error:
A field or property with the name 'Prep_By' was not found on the selected data source.
I don't understand what is the problem, the field 'Prep_By' is existing in my database.
Here's what I got:
private void LoadFeedback()
{
con = new SqlConnection(Connectiontxt);
con.Open();
SqlCommand cmd;
if (seardata == "")
{
cmd = new SqlCommand("SELECT [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID = '')", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
}
else {
cmd = new SqlCommand("SELECT [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID LIKE '%" + seardata + "%' or Title LIKE '%" + seardata + "%')", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
}
}
It means that gridrfqheader0 contains a binding reference to Prep_By, but you are not including it in your SELECT statement.
Try adding it:
cmd = new SqlCommand("SELECT [Articles_Tbl].[Prep_By], [Articles_Tbl].[Article_ID])...
As a side note, your conditional statements contain a lot of duplicate code. Consider moving the code that gets data into one location so that you do't have duplicate code. For example:
if (isNullOrEmpty(seardata))
{
cmd = new SqlCommand(your query);
}
else
{
cmd = new SqlCommand(your other query);
}
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ss");
gridrfqheader0.DataSource = ds.Tables["ss"];
gridrfqheader0.DataBind();
It can be further refactored, but this is a good start.
You are using Dataset to bind Grid, and in Grid you are using [Prep_By] field which not in your dataset.
So Simply just
Add "[Articles_Tbl].[Prep_By]" in your select statenment.
cmd = new SqlCommand("SELECT [Articles_Tbl].[Prep_By], [Articles_Tbl].[Article_ID], [Articles_Tbl].[Title], [Articles_Tbl].[Mod_Date], [Users_Tbl].[Name] FROM [Articles_Tbl] INNER JOIN [Users_Tbl] ON [Users_Tbl].[User_ID] = [Articles_Tbl].[Prep_By] where [Articles_Tbl].[Status] = 'Approved' and (Article_ID = '')", con);
make change in both sql queries..
If the grid has the column created with the source name Prep_By you have to select that column from the database.