How to add 2nd input on the KeyPress Function? - c#

How to Add key press in ' if(count<= 3)' condition. in this code we have define that if the input length is less than 3 or equal to 3 consider the input as quantity and then again go for the input if the input length is greater than 3 then consider the input as item code and search from database and quantity that we have entered it first time.
enter code here
private void SearchItem_KeyPress(object sender, KeyPressEventArgs e){
if (e.KeyChar == (char)Keys.Enter){
ItemLength = SearchItem.Text;
int count = 0;
for (int i = 0; i < ItemLength.Length; i++)
{
count++;
}
else if (count <= 3)
{
string qtyvalue = ItemLength;
SearchItem.Text = "1001";
SearchItem.Focus();
GetItemCode();
SearchItem.Text = Itemcodes;
//if (count <= 3 )
//{
SqlConnection conn = new SqlConnection(myconstring);
string query = "SELECT ItemCode, ItemDescription, SRate FROM ITEM WHERE ItemCode
= #ItemCode ";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#ItemCode", SearchItem.Text);
//cmd.Parameters.AddWithValue("#ItemDescription", SearchItem.Text);
conn.Open();
// DataTable dt = new DataTable(query);
SqlDataReader dr = cmd.ExecuteReader();
// da.Fill(dr);
if (dr.Read())
{
bool Found = false;
if (SaleItemList.Rows.Count > 0)
{
foreach (DataGridViewRow drrr in SaleItemList.Rows)
{
if (Convert.ToString(drrr.Cells[0].Value) == SearchItem.Text && drrr.Cells[1].Value == drr["ItemDescription"])
{
drrr.Cells[2].Value = Convert.ToString(Convert.ToInt16(qtyvalue) + Convert.ToInt16(drrr.Cells[2].Value));
drrr.Cells[4].Value = Convert.ToString(Convert.ToInt16(drrr.Cells[2].Value) * Convert.ToDouble(drrr.Cells[3].Value));
Found = true;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() != string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
}
}
if (!Found)
{
drr = dt.NewRow();
drr["ItemCode"] = dr.GetValue(0).ToString();
drr["ItemDescription"] = dr.GetValue(1).ToString();
drr["Qty"] = ItemLength;
drr["Rate"] = dr.GetValue(2).ToString();
drr["Amount"] = Convert.ToInt32(drr["Qty"]) * Convert.ToDouble(drr["Rate"]);
dt.Rows.Add(drr);
SaleItemList.DataSource = dt;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() != string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
SearchItem.Focus();
}
}
else
{
drr = dt.NewRow();
drr["ItemCode"] = dr.GetValue(0).ToString();
drr["ItemDescription"] = dr.GetValue(1).ToString();
drr["Qty"] = ItemLength;
drr["Rate"] = dr.GetValue(2).ToString();
drr["Amount"] = Convert.ToInt32(drr["Qty"]) * Convert.ToDouble(drr["Rate"]);
dt.Rows.Add(drr);
SaleItemList.DataSource = dt;
TotalAmount.Text = (from DataGridViewRow row in SaleItemList.Rows
where row.Cells[4].FormattedValue.ToString() !=
string.Empty
select Convert.ToInt32(row.Cells[4].FormattedValue)).Sum().ToString();
Clear();
SearchItem.Focus();
}
}
}
}
enter code here

Related

Combobox empty and doesnt dropdown

I created a combobox column in a datagridview. The problem is my combobox is empty, blank, and doesn't dropdown when i click on it. When i use the debuger, every properties and value are ok and the items exists and are link to the combobox. Please help me :(
Code : `
public Repair()
{
Main pp = new Main();
InitializeComponent();
this.label4.Text = pp.label3.Text;
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE FComponent IS NOT NULL";
}
else
{
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, RepairingTime FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
/**ArrayList list1 = new ArrayList(); //{ "C-C", "C-O", "Absence composant", "Mauvaise valeur", "Mauvais sens", "Mauvais composant" };
list1.Add("C-C");
list1.Add("C-O");**/
List<string> list1 = new List<string> { ("C-C"), ("C-O") };
combo.HeaderText = "FaultCodeByOp";
combo.DataPropertyName = "FaultCodeByOp";
combo.DropDownWidth = 120;
combo.FlatStyle = FlatStyle.Flat;
combo.Width = 90;
combo.DataSource = list1;
dataGridView1.Columns.AddRange(combo);
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for(int i=0;i<4;i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
for(int i=0;i<3;i++)
{
dataGridView2.Columns[i].ReadOnly = true;
}
}
}
/**private DataTable GetDescriptionTable()
{
DataTable l_dtDescription = new DataTable();
l_dtDescription.Columns.Add("FaultCodeByOp", typeof(string));
l_dtDescription.Rows.Add("C-O");
l_dtDescription.Rows.Add("C-C");
l_dtDescription.Rows.Add("Absence de composant");
l_dtDescription.Rows.Add("Mauvais composant");
l_dtDescription.Rows.Add("Mauvais sens");
l_dtDescription.Rows.Add("Mauvaise valeur");
return l_dtDescription;
}**/
private void textBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
string Var1 = textBox1.Text;
SqlCommand command = maConnexion.CreateCommand();
SqlCommand command1 = maConnexion.CreateCommand();
if (Program.UserType == "admin")
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailAndPass WHERE BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE SerialNum LIKE #SerialNum AND FComponent IS NOT NULL";
command1.CommandText = "SELECT Machine, BoardName, BoardNumber FROM FailAndPass WHERE SerialNum LIKE #SerialNum And FComponent IS NOT NULL";
}
}
else
{
if (textBox1.Text != String.Empty)
{
//command.Parameters.AddWithValue("#BoardName", Var1 + "%");
//command.Parameters.AddWithValue("#Machine", Var1 + "%");
command.Parameters.AddWithValue("#SerialNum", Var1 + "%");
command1.Parameters.AddWithValue("#SerialNum", Var1 + "%");
//command.Parameters.AddWithValue("#FComponent", Var1 + "%");
//command.CommandText = "SELECT * FROM FailOnly WHERE (BoardName LIKE #BoardName OR Machine LIKE #Machine OR SerialNum LIKE #SerialNum OR FComponent LIKE #FComponent) AND ReportingOperator IS NULL ";
command.CommandText = "SELECT Message, FComponent, ReadValue, ValueReference, FaultCodeByOp, RepairingTime FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL ";
command1.CommandText = "SELECT DISTINCT Machine, BoardName, BoardNumber FROM FailAndPass WHERE (SerialNum LIKE #SerialNum) AND ReportingOperator IS NULL AND FComponent IS NOT NULL";
}
}
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
SqlDataAdapter sda = new SqlDataAdapter(command);
SqlDataAdapter sda1 = new SqlDataAdapter(command1);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
sda.Fill(dt);
sda1.Fill(dt1);
DataColumn dcIsDirty = new DataColumn("IsDirty", typeof(bool));
DataColumn dcIsDirty1 = new DataColumn("IsDirty", typeof(bool));
dcIsDirty.DefaultValue = false;
dcIsDirty1.DefaultValue = false;
dt.Columns.Add(dcIsDirty);
dt1.Columns.Add(dcIsDirty1);
dataGridView1.DataSource = dt;
dataGridView2.DataSource = dt1;
maConnexion.Close();
dataGridView1.Columns[6].Visible = false;
dataGridView2.Columns[3].Visible = false;
}
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.IsCurrentRowDirty)
{
dataGridView1.Rows[e.RowIndex].Cells[6].Value = true;
}
}
private void metroButton1_Click(object sender, EventArgs e)
{
SqlConnection maConnexion = new SqlConnection("Server= localhost; Database= Seica_Takaya;Integrated Security = SSPI; ");
maConnexion.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[6].Value != null) && (bool)row.Cells[6].Value)
{
SqlCommand command = maConnexion.CreateCommand();
command = new SqlCommand("update FailAndPass set FaultCodeByOp=#Fault, RepairingDate=#RD, RepairingTime = #RT, ReportingOperator=#RO WHERE SerialNum=#Serial", maConnexion);
command.Parameters.AddWithValue("#Fault", row.Cells[4].Value != null ? row.Cells[4].Value : DBNull.Value);
command.Parameters.AddWithValue("#RD", DateTime.Today.ToString("d"));
command.Parameters.AddWithValue("#RT", row.Cells[5].Value != null ? row.Cells[5].Value : DBNull.Value);
command.Parameters.AddWithValue("#RO", this.label4.Text);
command.Parameters.AddWithValue("#Serial", this.textBox1.Text);
command.ExecuteNonQuery();
}
}
maConnexion.Close();
this.Hide();
Repair rep = new Repair();
rep.Show();
}
private void metroButton2_Click(object sender, EventArgs e)
{
this.Hide();
Main ff = new Main();
ff.Show();
}
/**private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex > -1)
{
// Bind grid cell with combobox and than bind combobox with datasource.
DataGridViewComboBoxCell l_objGridDropbox = new DataGridViewComboBoxCell();
// Check the column cell, in which it click.
if (dataGridView1.Columns[e.ColumnIndex].Name.Contains("FaultCodeByOp"))
{
// On click of datagridview cell, attched combobox with this click cell of datagridview
dataGridView1[e.ColumnIndex, e.RowIndex] = l_objGridDropbox;
l_objGridDropbox.DataSource = GetDescriptionTable(); // Bind combobox with datasource.
l_objGridDropbox.ValueMember = "FaultCodeByOp";
l_objGridDropbox.DisplayMember = "FaultCodeByOp";
}
}
}**/
}`
It seems that setting the DataGridViewComboBoxColumn to ReadOnly evokes this error in the loop:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
I am trying to find out why exactly..... for now avoid setting it to ReadOnly with a simple if clause:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < 4; i++)
{
if (!(dataGridView1.Columns[i] is DataGridViewComboBoxColumn))
{
dataGridView1.Columns[i].ReadOnly = true;
}
}
}
EDIT:
The Problem seems to be dataGridView1.Columns[0]. This column does not like it to be set with values or to be set to ReadOnly. It also seems not to have any name (tested it) which is very weird. Nontheless, if you start your loop at 1 the error will go away and you can have even your DataGridViewComboBoxColumn to be set to ReadOnly = true without the if clause:
for (int i = 1; i < 4; i++)
{
dataGridView1.Columns[i].ReadOnly = true;
}
Okay guys. I've done a new test.
Here is my test code :
combo.DataSource = list1;
if(combo.IsDataBound)
{
MessageBox.Show("TRUE");
}
else
{
MessageBox.Show("FALSE");
}
It seems that combo.datasource = list1 have all my value ("C-C" and "C-O"). But when i launch the debugger or launch the application, the messagebox which appear is the second one where combo.isdatabound = false. Normally, it should be True?

c# - SQLITE and dataGridView1

i search and i search buy i cant find a solution
this is my code
private void pointage_Load(object sender, EventArgs e)
{
sql = "SELECT firstname, lastname FROM company";
command = new SQLiteCommand(sql, connectiondb);
DataSet1 mydata = new DataSet1();
SQLiteDataAdapter zz = new SQLiteDataAdapter(sql, connectiondb);
zz.Fill(mydata.Tables["DataTable1"]);
int i;
SQLiteDataReader reader = command.ExecuteReader();
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[1].Clone();
while (reader.Read())
{
for (i = 0; i <= System.Convert.ToUInt32(reader["id"]); i++)
{
row = this.dataGridView1.Rows[i];
row.Cells["Column10"].Value = reader["firstname"].ToString();
row.Cells["Column9"].Value = reader["lastname"].ToString();
}
}
}
what i need do, if i leave this lines
row = this.dataGridView1.Rows[i];
row.Cells["Column10"].Value = reader["firstname"].ToString();
row.Cells["Column9"].Value = reader["lastname"].ToString();
and i put just
MessageBox.Show(reader["firstname"].ToString());
that will work but when i do that
for (i = 0; i <= System.Convert.ToUInt32(reader["id"]); i++)
{
row = this.dataGridView1.Rows[i];
row.Cells["Column10"].Value = reader["firstname"].ToString();
row.Cells["Column9"].Value = reader["lastname"].ToString();
}
that not work :'(
what ill do, help me please
ok guys finaly i find the solution :D
while (reader.Read())
{
i = System.Convert.ToInt32(reader["id"].ToString());
dataGridView1.Rows.Add();
MessageBox.Show(System.Convert.ToString(i));
DataGridViewRow R = dataGridView1.Rows[i-1];
R.Cells["Column9"].Value = reader["firstname"].ToString();
R.Cells["Column10"].Value = reader["lastname"].ToString();
}

ASP.NET Listbox not selecting multiple values

I have a listbox in my webform from which I am trying to select multiple values, but I am only getting last selected values. I have tried in two ways. First I explicitly added list items:
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple" AutoPostBack="True">
<asp:ListItem>teama</asp:ListItem>
<asp:ListItem>teamb</asp:ListItem>
</asp:ListBox>
Second, I tried to bind to a table in a database:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox2.SelectionMode = ListSelectionMode.Multiple;
string scon = ConfigurationManager.ConnectionStrings["Test_AthiraConnectionString"].ConnectionString;
SqlConnection con=new SqlConnection(scon);
con.Open();
SqlCommand cmd = new SqlCommand("select department from department", con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ListBox2.DataSource = ds;
ListBox2.DataValueField = "department";
ListBox2.DataTextField = "department";
ListBox2.DataBind();
con.Close();
}
}
Then I tried these different methods to select multiple items on buttonclick event
First:
string k =null ,k1 = null;
foreach (int i in ListBox2.GetSelectedIndices())
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
Second:
foreach (ListItem li in ListBox2.Items)
{
if (li.Selected == true)
{
k += li.Text + "/";
Response.Write(k);
}
}
Third:
k = String.Join("/", ListBox2.Items
.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i=>i.Value)
.ToArray());
Response.Write(k);
Fourth:
for (int i = ListBox2.Items.Count - 1; i >= 0; i--)
{
if (ListBox2.Items[i].Selected == true)
{
k1 = ListBox2.Items[i].Text + "/";
k += k1;
Response.Write(k);
}
}
But none of them seem to work. I am getting only the last selected value.
You may access the items in the list as follow and check their properties.
IEnumerator ie = ListBox2.Items.GetEnumerator();
while (ie.MoveNext())
{
ListItem li = (ListItem)ie.Current;
//Use ListItem here
}
please try below code, It will return coma separator string for Listbox selected value
public string GetSelectedValues()
{
string selectedVal = string.Empty;
int i = 0;
foreach (int index in lstbox.GetSelectedIndices())
{
if (i == 0)
selectedVal = lstbox.Items[index].Value;
else
selectedVal = selectedVal + ";" + lstbox.Items[index].Value.ToString();
i++;
}
return selectedVal ;
}

how to use repeater iteratively?

I have one repeater which displays the list of puja.i have also used one datalist to display the names of temples.whenever i click on search it displays only the last value of the repeater i.e it is taking only the last value of the repeater....my question is how to use loop inside a repeater???
here is my code behind how i used datalist and repeater:
protected void Page_Load(object sender, EventArgs e)
{
//lblnodatafound.Visible = true;
//lbldatafound.Visible = false;
if (Request.QueryString["search"] != null)
{
var dt = new DataTable("Data");
String source = Request.QueryString["search"];
var splitseparator = new string[] { " " };
String[] result = source.Split(splitseparator, StringSplitOptions.RemoveEmptyEntries);
foreach (String s in result)
{
if (IsAlphaNumeric(s) == true)
{
var dttemp = new DataTable();
dttemp = fnsearch(s);
dt.Merge(dttemp, true);
}
}
if (dt.Rows.Count != 0)
{
int count = dt.Rows.Count;
if (dt.Rows.Count > 0)
{
DataList1.DataSource = dt;
DataList1.DataBind();
lblnodatafound.Visible = false;
lbldatafound.Visible = true;
//added the repeater to display the list of puja
for (int i = 0; i < dt.Rows.Count; i++)
{
String id = dt.Rows[i]["id"].ToString();
string query = "select puja.id,puja.name as puja_name, mandir.name as mandir_name from puja,mandir where mandir.id= puja.with_mandir and puja.with_mandir = '" + id + "'";
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
adp.Fill(dt1);
conn.Close();
if (dt1.Rows.Count > 0)
{
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
foreach (RepeaterItem repeatItem in Repeater1.Items){
Repeater1.DataSource = dt1;
Repeater1.DataBind();
}
}
}
}
}
else
{
lblnodatafound.Visible = true;
lbldatafound.Visible=false;
}
}
}
Try to change this line:
if (dt1.Rows.Count > 0)
for something like:
for(int i = 0; i < dt1.Rows.Count; i++)
And this one:
lblmandirpuja.Text = "Poja in " + dt1.Rows[0]["mandir_name"];
The 0 for the i:
lblmandirpuja.Text = "Poja in " + dt1.Rows[i]["mandir_name"];

no row at position 0

I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}

Categories

Resources