I am trying to give multiple select commands in single button.
Example:
Datewise search,name wise,Product wise search in a single show Button.
But this search can be random like either name wise search alone can be done
or name and product wise search can be done.
But this should done in a single show button only..
Plz help me with a example code..
This is not a coding doubt,this is more likely a logic doubt,For this you have lot of options here you can perform some SQL Query concatenations Or some If..else...elseIf statements,something like this :
protected void btnSave_Click(object sender, EventArgs e)
{
if (ddpcustomer.SelectedIndex == 0 && ddpproperty.SelectedIndex == 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusCheckinDate(inputField.Text, inputField1.Text, userId, Cid);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 && ddpproperty.SelectedIndex == 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithCustNameCheckinDate(inputField.Text, inputField1.Text, userId, Cid,ddpcustomer.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 )
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithPnameCheckinDate(inputField.Text, inputField1.Text, userId, Cid, ddpproperty.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
else if (ddpcustomer.SelectedIndex != 0 && ddpproperty.SelectedIndex != 0)
{
DataSet ds1 = Tbl_MasterBooking.getDetailsforBookingSummaryWithoutStatusWithPnameandCustNameCheckinDate(inputField.Text, inputField1.Text, userId, Cid, ddpproperty.SelectedItem.Text, ddpcustomer.SelectedItem.Text);
GVBookingSummary.DataSource = ds1;
GVBookingSummary.DataBind();
GridView1.DataSource = ds1;
GridView1.DataBind();
}
}
If you want to do search based on One filter you'd better use a DropDownList and search based on the selected value or ... but if searching in multiple data collections is your doubt I'll provide you a code snippet below :
private class Product
{
public string Name;
public double Price;
public string ToString()
{
return Name + " : " + Price.ToString() + "$";
}
}
private void button1_Click(object sender, EventArgs e)
{
List<string> names = new List<string>();
names.Add("Jack");
names.Add("John");
names.Add("Nick");
names.Add("Rock");
List<Product> products = new List<Product>();
products.Add(new Product { Name = "Laptop", Price = 1000 });
products.Add(new Product { Name = "Tablet", Price = 750 });
products.Add(new Product { Name = "Rock", Price = 1 });
List<DateTime> dates = new List<DateTime>();
dates.Add(DateTime.Now.AddDays(-1));
dates.Add(DateTime.Now);
dates.Add(DateTime.Now.AddDays(1));
lblOutput.Text = "";
foreach (string name in names)
{
if (name == txtSearch.Text)
lblOutput.Text += name + "[Name] ";
}
foreach (Product product in products)
{
if (product.Name == txtSearch.Text)
lblOutput.Text += product.ToString();
}
foreach (DateTime date in dates)
{
DateTime dt;
if (DateTime.TryParse(txtSearch.Text, out dt))
if (date == dt)
lblOutput.Text = date.Date.ToShortDateString();
}
}
Also if you want to stop searching as soon as you've found a match, you can put a return after each match-found code block, for example:
if (name == txtSearch.Text)
{ lblOutput.Text += name + "[Name] "; return;}
I hope it helps.
I hope this would do.You may setup the options you like.
public class Parameters
{
//Properties.
public string CompanyName
{
get;set;
}
public string ProductName
{
get;set;
}
public string Design
{
get;set;
}
public string Size
{
get;set;
}
}
private void button1_Click(object sender, EventArgs e)
{
Parameters para = new Parameters();
if (cbxCompanyName.Text.Trim().Length != 0)
{
para.CompanyName = "'" + this.cbxCompanyName.Text + "'";
}
if (cbxProductName.Text.Trim().Length != 0)
{
para.ProductName = "'" + this.cbxProductName.Text + "'";
}
if (cbxDesign.Text.Trim().Length != 0)
{
para.Design = "'" + this.cbxDesign.Text + "'";
}
}
public void test(Parameters paras)
{
try
{
con = new SqlConnection(source);
con.Open();
string select;
select = "SPGetSaleRegCulture ";
DataSet ds = new DataSet();
cmd = new SqlCommand(select, con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Company", paras.CompanyName);
cmd.Parameters.AddWithValue("#Product", paras.ProductName);
cmd.Parameters.AddWithValue("#Design", paras.Design);
cmd.Parameters.AddWithValue("#Size", paras.Size);
da.SelectCommand = cmd;
da.Fill(ds, "SaleRegister");
}
catch (Exception ex)
{
throw ex;
}
}
Related
In DataGridView I have two ComboBox columns:
private string controlFrom= "cmbMachineAndOpIDFrom";
private string controlTo = "cmbMachineAndOpIDTo";
I want to check those two-columns combination for duplicates. If duplicate exists or null the record must be cancelled with message for the user. I try to use RowValidating event for that:
private void dgvTransfers_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
string columName = dgvTransfers.Columns[e.ColumnIndex].Name;
e.Cancel = IsDuplicateExists(columName);
}
The code of IsDuplicateExist:
private bool IsDuplicateExists(string colName)
{
bool res = false;
int existingRowID = 0;
if (colName.Equals(controlFrom) || colName.Equals(controlTo))
{
int cmbFrom = Convert.ToInt32(Helper.GetSelectedRowValueInDGV(dgvTransfers, controlFrom));
int cmbTo = Convert.ToInt32(Helper.GetSelectedRowValueInDGV(dgvTransfers, controlTo));
if (cmbFrom == 0 || cmbTo == 0)
{
res = true;
}
//Check for duplicates
existingRowID = Helper.GetDuplicatedRowIndex(cmbFrom, cmbTo, dgvTransfers, controlFrom, controlTo);
if (existingRowID > 0)
{
//Already exists
GoToDublicatedRecord(existingRowID, dgvTransfers);
res = true;
}
}
return res;
}
I always get 0 value for cmbFrom and cmbTo using method GetSelectedRowValueInDGV:
public static string GetSelectedRowValueInDGV(DataGridView dgvName, string columnName)
{
string res = "0";
if (dgvName.SelectedRows.Count > 0)
{
var vl = dgvName.SelectedRows[0].Cells[columnName].Value;
if (vl.ToString()!=string.Empty && vl != null && vl != DBNull.Value)
{
res = dgvName.SelectedRows[0].Cells[columnName].Value.ToString();
}
}
return res;
}
So first question is why I do not get selected cell value?
Here comes the second part of problem. Since both values are zeroes I get e.Cancel = true. Here I expect editing to be cancelled but instead I get error
'Operation did not succeed because the program cannot commit or quit a
cell value change.'
at row dgvName.DataSource = dt; in CellValueChanged event where GetDataForGridView is called to get data from SQL SP:
public static bool GetDataForGridView(DataGridView dgvName, string storedProcedureName, params SqlParameter[] arrParam)
{
DataTable dt = new DataTable();
bool result;
// Open the connection
using (SqlConnection sqlConn = new SqlConnection(strConn))
{
try
{
sqlConn.Open();
// Define the command
using (SqlCommand sqlCmd = new SqlCommand())
{
sqlCmd.Connection = sqlConn;
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.CommandText = storedProcedureName;
// Handle the parameters
if (arrParam != null)
{
foreach (SqlParameter param in arrParam)
{
sqlCmd.Parameters.Add(param);
}
}
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd))
{
da.Fill(dt);
result = true;
}
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
result = false;
}
dgvName.AutoGenerateColumns = false;
dgvName.DataSource = dt;
sqlConn.Close();
}
return result;
}
UPDATED
Here is how both Comboboxes are populated:
private void FrmTransfers_Load(object sender, EventArgs e)
{
Helper.GetDataForGridView(dgvTransfers, "pp_sp_Transfers", null);
PopCombo(cmbMachineAndOpIDFrom, "MachineAndOpID",0,0);
PopCombo(cmbMachineAndOpIDTo, "MachineAndOpID",0,0);
}
private void PopCombo(DataGridViewComboBoxColumn combo, string valMember, int parValue1, int parValue2)
{
DataTable dtMO = Helper.ExecuteDataTable("pp_sp_MachineAndOp",
new SqlParameter("#MachineAndOpID", SqlDbType.Int) { Value = parValue1 },
new SqlParameter("#Seq", SqlDbType.Int) { Value = parValue2 });
//Add field to be displayed
dtMO.Columns.Add("ToShow", typeof(string), "'Seq: ' + Seq + ' ID: ' + MachineAndOpID + ' (' + OperationID + ') ' + Operation + ' + ' + Machine");
// bind data table into combo box.
combo.DataSource = dtMO;
combo.DisplayMember = "ToShow";
combo.ValueMember = valMember;
}
Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.
Im trying to create a login form for a website using ms access database. I'm using visual studio 2010 c# and access 2013. For some reason I can't get it to log in. I'm really new to this so any help is appreciated.
DataLayer:
public class DataConnector
{
protected OleDbDataAdapter DataAdapter1 = new OleDbDataAdapter();
public string ErrorMessage = "";
public DataConnector(string ConnectionString)
{
OleDbConnection Connection1 = new OleDbConnection(ConnectionString);
this.DataAdapter1.SelectCommand = new OleDbCommand("", Connection1);
this.DataAdapter1.InsertCommand = new OleDbCommand("", Connection1);
}
public DataTable DataSelect(string query)
{
DataTable dt = new DataTable();
try
{
DataAdapter1.SelectCommand.CommandText = query;
DataAdapter1.SelectCommand.Connection.Open();
DataAdapter1.Fill(dt);
DataAdapter1.SelectCommand.Connection.Close();
ErrorMessage = "";
}
catch(Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.SelectCommand.Connection.Close();
}
return dt;
}
public int DataInsert(string query)
{
int Result = 0;
try
{
DataAdapter1.InsertCommand.CommandText = query;
DataAdapter1.InsertCommand.Connection.Open();
Result = DataAdapter1.InsertCommand.ExecuteNonQuery();
DataAdapter1.InsertCommand.Connection.Close();
ErrorMessage = "";
return Result;
}
catch (Exception err)
{
ErrorMessage = err.Message;
DataAdapter1.InsertCommand.Connection.Close();
return 0;
}
}
public int DataUpdate(string query)
{
return DataInsert(query);
}
public int DataDelete(string query)
{
return DataInsert(query);
}
}
Default.aspx.cs:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
DataLayer.DataConnector dat = new DataLayer.DataConnector("Provider=Microsoft.ACE.OLEDB.12.O;"+"Data Source='"+Server.MapPath("site_database.accdb")+"'; Persist Security Info=False;");
DataTable dt = dat.DataSelect("select UserID from tbl_login where Username = '" + txtUsername.Text + "' and Password = '"+ txtPassword.Text +"' ");
if (dt.Rows.Count > 0)
{
Response.Redirect("members_area.aspx");
}
else
lblerror.Text = "Login failed";
}
}
I'm not getting any errors and I just can't figure it out. When I try to log in it just stays on the default.aspx page.
Part of the problem could very well be that PASSWORD is a reserved word in Access SQL, so if you want to use it as a field name in a query you should surround it in square brackets, e.g.
... WHERE Username = ... AND [Password] = ...
Note also that you really should be using a parameterized query in case Little Bobby Tables tries to log in.
I have a DataGridView created in C# windows forms and checkboxColumn added to it. The DataGridView is populated with other columns like Sno, AccountNo, Name, Salary (Sno is identitycolumn and primarykey).
I want to delete a row (using stored procedure) by selecting the checkbox and on button click which is out side DataGridView. Error at "FindControl".
Stored Procedure:
Create Procedure uspDeleteSelectedRow
As
Delete from EmpDetails where Sno=Sno
Go
private void btnDelete_Click(object sender, EventArgs e)
{
//Create String Collection to store IDs of
//records to be deleted
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
//Loop through GridView rows to find checked rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)dataGridView1.Rows[i].
Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = dataGridView1.Rows[i].Cells[1].ToString();
idCollection.Add(strID);
}
}
}
if (idCollection.Count > 0)
{
//Call the method to Delete records
DeleteMultipleRecords(idCollection);
// rebind the GridView
dataGridView1.DataBind();
}
else
{
lblMessage.Text = "Please select any row to delete";
}
}
private void DeleteMultipleRecords(StringCollection idCollection)
{
//Create sql Connection and Sql Command
SqlConnection con = new SqlConnection(Helper.ConnectionString);
SqlCommand cmd = new SqlCommand();
string IDs = "";
foreach (string id in idCollection)
{
IDs += id.ToString() + ",";
}
try
{
string test = IDs.Substring
(0, IDs.LastIndexOf(","));
string sql = "Delete from EmpDetails" + " WHERE ID in (" + test + ")";
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
string errorMsg = "Error in Deletion";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
con.Close();
}
}
Let say this is your stored procedure:
ALTER PROCEDURE [dbo].[sp_ToDeleteEmpDetails] #Sno int
/*
(
#parameter1 int = 5,
#parameter2 datatype OUTPUT
)
*/
AS
DELETE FROM EmpDetails
WHERE Sno = Sno
RETURN
You don't need a StringCollection to delete or call the stored procedure.
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
bool IsBool = false;
if (bool.TryParse(item.Cells[1].EditedFormattedValue.ToString(), out IsBool)) //<--Where: The ColumnIndex of the DataGridViewCheckBoxCell
{
using (SqlConnection con = new SqlConnection(Helper.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("sp_ToDeleteEmpDetails", con))
{
try {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#sno", SqlDbType.Int).Value = item.Cells[0].EditedFormattedValue.ToString(); //<--Where: The ColumnIndex of the Primary key from your DataGridView
dataGridView1.Rows.RemoveAt(item.Cells[0].RowIndex);
con.Open();
cmd.ExecuteNonQuery();
} catch (Exception) {
throw;
}
finally
{
con.Close();
}
}
}
}
}
}
Please let me know if you have some encountered problem from my given answer.
Try this solution. In my code I have class and pass a list of it to gridview as my datasource.
//Class
public class User
{
public bool Selected { get; set; }
public string UserName { get; set; }
}
//Create a list and bind to the data grid view
private void Form1_Load(object sender, EventArgs e)
{
var users = new List<User> { new User { UserName = "Jobert", Selected = false }, new User { UserName = "John", Selected = true }, new User { UserName = "Leah", Selected = true }, new User { UserName = "Anna", Selected = false } };
dataGridView1.DataSource = users;
}
//On delete
private void btnDelete_Click(object sender, EventArgs e)
{
//get data back from the source
var source = dataGridView1.DataSource as List<User>;
var selectedItems = source.Where(x => x.Selected).ToList();
foreach (var item in selectedItems)
{
//perform the delete
}
}
I have 2 db tables:
ProductGroup(GroupID, GroupName, ...)
Product(ProductID, ProductName, GroupID, ...)
Now I want to display the ProductGroup and the Product Table in a TreeView.
I am using an Entity Model and I dont now how to bind 2 Tables to 1 TreeView.
I am looking forward to some answers! THX
public partial class Form1 : Form
{
private string TextFields=string.Empty;
private string TagFields=string.Empty;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FillTree();
}
void FillTree()
{
DataSet mds = new DataSet();
DataSet dds = new DataSet();
string ssql;
TextFields = "GroupName";
TagFields = "GroupID";
this.treeView1.Nodes.Clear();
ssql = "select GroupID, GroupName from productgroups ";
mds = DB.GetInstance.GetDataSet( ssql);
if(mds!=null)
insert1LevelNodes(null,mds.Tables[0]);
ssql="select ProductID, ProductName, GroupID from products";
dds = GetDataSet(ssql);
if(dds!=null)
{
for(short i = 0;i<this.treeView1.Nodes.Count;i++)
{
TextFields = "ProductName";
TagFields = "ProductID";
insert1LevelNodes(this.treeView1.Nodes[i],dds.Tables[0] );
}
}
dds.Clear();
dds.Dispose();
}
void insert1LevelNodes(TreeNode parentNode, DataTable dt)
{
string sNodeText = "";
string sNodeTag = "";
string[] aTexts = this.TextFields.Split(',');
string[] aTags = this.TagFields.Split(',');
for(int i=0; i< dt.Rows.Count; i++ )
{
sNodeText = "";
sNodeTag = "";
for(int k=0;k<dt.Columns.Count;k++)
{
for(short j=0;j<aTexts.Length;j++)
if(aTexts[j].Equals(dt.Columns[k].ColumnName))
sNodeText+=dt.Rows[i][k].ToString() + ":";
for(short j=0;j<aTags.Length;j++)
if(aTags[j].Equals(dt.Columns[k].ColumnName))
sNodeTag+=dt.Rows[i][k].ToString() + ",";
}
if(sNodeText.Length>0) sNodeText = sNodeText.TrimEnd(':');
if(sNodeTag.Length>0) sNodeTag = sNodeTag.TrimEnd(',');
if(sNodeText==string.Empty) return;
TreeNode newNode=new TreeNode(sNodeText);
newNode.Tag = sNodeTag;
if(parentNode==null)
treeView1.Nodes.Add(newNode);
else
parentNode.Nodes.Add(newNode);
}
}
DataSet GetDataSet(string ssql)
{
/// Your function to get Dataset from your Database
}
}