C#: Add "Select" item to Dynamic Fill ComboBox method - c#

I need to add "Select" at index 0 without know DataTable columns count or name because this method in DataAccessLayer and will use later`
// ComboBox Fill Method
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}

I have solved this issue by the following code.
Thanks for all ...
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drow = dt.NewRow();
for (int i = 0; i < dt.Columns.Count ; i++)
{
if (dt.Columns[i].ColumnName == cboDisplayMember)
{
drow[i] = "Select";
}
else if (dt.Columns[i].ColumnName == cboValueMember)
{
drow[i] = 0;
}
else
{
drow[i] = null;
}
}
dt.Rows.InsertAt(drow, 0);
cbo.DataSource = dt;
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}

Just put this line in your ComboBoxFill() function.
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
{
con.Open();
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
cbo.DataSource = dt;
DataRow newRow = dt.NewRow();
newRow[0] = "Select";
dt.Rows.InsertAt(newRow, 0);
cbo.DisplayMember = cboDisplayMember;
cbo.ValueMember = cboValueMember;
cbo.SelectedIndex = 0;
con.Close();
}
It will add "Select" at postion 0

Related

C# Checkedlistbox data binding

I have a checkedlistBox in C# that I am filling from sql-server.
I need to insert the checkeditems when creating a new record and I need to update the previous selected items of a certain record.
First I am trying to read the selected item of a specific record so i tried the following:
I compare the value member of every item with the list I am getting from the sql query if it matches I check the item.
So I need to use something like the value option.
if(checkedListBox1.Items.IndexOf(i).**Value**
string sql = #"select cs.id from[dbo].[Channel_availableSpecs] cas inner join[dbo].[Channel_specs] cs on cas.ChennelSpec_Id = cs.id
where cas.Channel_Id =" + val + "order by cs.id";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dta = new DataTable();
da.Fill(dta);
foreach (DataRow dr in dta.Rows)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.Items.IndexOf(i).**Value** == dr.ToString()) checkedListBox1.SetItemCheckState(i, CheckState.Checked);
}
conn.Close();
}
}
Fill Checkedlistbox
public static void FillCheckedListox(CheckedListBox checkedListBox, string query,string displayMember, string valueMember) {
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
((ListBox)checkedListBox).DataSource = dt;
((ListBox)checkedListBox).DisplayMember = displayMember;
((ListBox)checkedListBox).ValueMember = valueMember;
}
}
}
This is the solution
private void selectSpecs(DataTable table)
{
while (checkedListBox1.CheckedIndices.Count > 0)
{
checkedListBox1.SetItemChecked(checkedListBox1.CheckedIndices[0], false);
}
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
DataRow r;
r = ((DataRowView)this.checkedListBox1.Items[i]).Row;
string val = (r[this.checkedListBox1.ValueMember]).ToString();
channelsSpecs.Add(Convert.ToInt32(val));
r = null;
for (int j = 0; j < table.Rows.Count; j++)
foreach (DataRow dataRow in table.Rows)
foreach (var item in dataRow.ItemArray) if (val.ToString() == item.ToString()) checkedListBox1.SetItemChecked(i, true);
}
}

How to Delete Row By ID From Datatable and Database

Here is full code at the moment what I have done. So basically I'm creating a DataTable, then I'm connecting my DataTable with a database. I can edit person by ID, but I don't know how to delete person by ID. I want a full row to be deleted.
As well, in the part where I edit the DataTable, if I choose not to edit table, I get some null reference error
Object reference not set to an instance of an object.
My code:
/*
* Creating DataTable
*/
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Vards", typeof(string)));
dt.Columns.Add(new DataColumn("Uzvards", typeof(string)));
/*
* Connecting to DataBase
*/
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM PERSONA", con);
con.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
DataRow dr = dt.NewRow();
dr["ID"] = dataReader["ID"];
dr["Vards"] = dataReader["Vards"];
dr["Uzvards"] = dataReader["Uzvards"];
dt.Rows.Add(dr);
}
con.Close();
dt.AcceptChanges();
PrintDataTable(dt);
Console.WriteLine();
/* Edit Person in DataTable */
Console.WriteLine("Kuru ID vēlaties labot?");
int labosana = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vai tiešām vēlaties labot šo ierakstu?");
string vaiLabot = Console.ReadLine();
if (vaiLabot == "yes")
{
Console.WriteLine("Ievadiet jauno vārdu:");
string vards = Console.ReadLine();
Console.WriteLine("Ievadiet jauno uzvārdu:");
string uzvards = Console.ReadLine();
dt.Rows[labosana-1]["Vards"] = vards;
dt.Rows[labosana-1]["Uzvards"] = uzvards;
}
else
{
Console.WriteLine("Jūs atteicāties labot!");
}
/*
* Adding Edited Person to Database
*/
OleDbCommand upCmd = new OleDbCommand("UPDATE PERSONA SET Vards=?,Uzvards=? WHERE ID=?", con);
upCmd.Parameters.Add(new OleDbParameter("#Vards",OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#Uzvards", OleDbType.VarChar));
upCmd.Parameters.Add(new OleDbParameter("#ID", OleDbType.Integer));
foreach(DataRow dro in dt.GetChanges().Rows)
{
if (dro.RowState == DataRowState.Modified)
{
upCmd.Parameters[0].Value = dro[1];
upCmd.Parameters[1].Value = dro[2];
upCmd.Parameters[2].Value = dro[0];
con.Open();
upCmd.ExecuteNonQuery();
con.Close();
}
}
I tried a ton of code. But none of them seems to work. Tried something like this to delete by the Name.
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
dr.Delete();
}
Use this code for deleting by Id from database:
public int DeleteById(int Id)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"datubaze.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("DELETE FROM PERSONA WHERE ID = #ID", con);
cmd.Parameters.Add(new OleDbParameter("ID", Id));
return cmd.ExecuteNonQuery();
}
Updated: try this -- To delete from the DataTable
DataRow rowToBeDeleted;
for(int i = dt.Rows.Count-1; i >= 0; i--)
{
DataRow dr = dt.Rows[i];
if (dr["Vards"] == "Name")
rowToBeDeleted = dr;
}
dt.Rows.Remove(rowToBeDeleted );
Or if using LINQ, you can also do something like
var dr = dt.AsEnumerable().Where(row => row.Field<string>("Vards") == "Name").SingleOrDefault();
dt.Rows.Remove(dr);

How to append row from one dataset to another dataset?

I want to add one row from dataset ds to dc every time. and I want to keep updating the Gridview to bigger the table. But when I try it in my code. the Gridview can only display one row according to what i input in the textbox.
public partial class TestGridview : System.Web.UI.Page
{
int count = 0;
DataSet dc = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string text = TextBox1.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
string str = "SELECT * FROM XML WHERE [Part_Numbber] = #textInput";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("textInput", text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "XML");
if (count == 0)
{
dc = ds.Clone();
count ++;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].ItemArray[0].ToString() != "NULL")
{
dc.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
}
}
GridView1.DataSource = dc;
GridView1.DataBind();
}
}
You can make use of below code to append rows from 1 DT to other final DT. LikeWise
foreach (DataRow dataRow in dt2.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt3.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt4.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}

I need to retrieve the vaL1 in c# using ,search by red and blue value and find two values

This value (val1) I'm passing through url (I mean this operation as jobong filter option in checkbox list, filtering by selection index then passing through another page and retrieve through database):
Default Page 3: /WebSite4/Default4.aspx?vaL1=blue,red
This retrieving form page to view in page.
Default Page 2:
public void grid()
{
con.Open();
cmd = new SqlCommand("select * from lady_cloth where color in('" + Request.QueryString["vaL1"] + "')", con);
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
DataSet ds3 = new DataSet();
da1.Fill(ds3);
con.Close();
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
SqlConnection con = new SqlConnection("Data Source=xxxx;Initial Catalog=e_commerce;User ID=sa;Password=xxx");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Label1.Text = Request.QueryString["Item"];
//Label2.Text = Request.QueryString["Color"];
//grid();
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
}
string sql = "SELECT * FROM lady_cloth WHERE color IN (SELECT Value FROM #Colours)";
cmd = new SqlCommand(sql, con);
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
//parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
con.Open();
adapter.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}
I think your problem is that you are not separating your items, so your SQL ends up looking like:
select *
from lady_cloth
where color in('blue,red')
Whereas what you would really want is
select *
from lady_cloth
where color in('blue','red')
If you are using SQL Server 2008 or later then I would recommend using table-valued parameters. The first step would be to create your type:
CREATE TYPE dbo.StringList TABLE (Value NVARCHAR(MAX));
I tend to just create generic types that can be easily reused, but this would be your call.
Then in your method you would need to split your values into an array and add them to a datatable:
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
You can then add this table to your command as a parameter:
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
cmd = new SqlCommand(sql, con);
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
cmd.Parameters.Add(parameter);
Finally, You can reduce your code by just initialising the SqlDataAdapter with your SQL and connection:
public void grid()
{
var colourTable = new DataTable();
colourTable.Columns.Add("Value", typeof(string));
var colours = Request.QueryString["vaL1"].Split(',');
for (int i = 0; i < colours.Length; i++)
{
var newRow = colourTable.NewRow();
newRow[0] = colours[i];
colourTable.Rows.Add(newRow);
}
string sql = "SELECT * FROM lady_clock WHERE Color IN (SELECT Value FROM #Colours)"
DataSet ds3 = new DataSet();
using (var adapter = new SqlDataAdapter(sql, con))
{
var parameter = new SqlParameter("#Colours", SqlDbType.Structured);
parameter.Value = colourTable;
parameter.TypeName = "dbo.StringList";
adapter.Parameters.Add(parameter);
con.Open();
da1.Fill(ds3);
}
if (ds3.Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ds3;
GridView1.DataBind();
}
else
{
}
}

Adding a column to a datatable and adding data

How can I add a column to a datatable and add data to each row based on a condition.
This is what I am trying to do
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
Dictionary<string, string> items = new Dictionary<string, string>();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CODE, TITLE FROM tblProducts";
OleDbDataReader dbread = cmd.ExecuteReader();
while (dbread.Read())
{
productCode = (string)dbread["ProductCode"];
productTitle = items[productCode];
items.Add(productCode, productTitle);
}
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < items.Count; i++)
{
if (dr["ProductCode"].ToString().Equals(productCode))
{
//here I want to add a new column and add data (productTitle) to the column
}
}
}
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];
dt.Columns.Add("ColumnName", typeof(DataType));
if (dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
Further i would extend the code to avoid NullReferenceException
if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}
http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx

Categories