c# - SQLITE and dataGridView1 - c#

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();
}

Related

How to remain the treeview after redirect to another page?

Im currently using this method to bind my treeview, After i expand the treeview and click the node, it will redirect to another page, and then the treeview will be refresh to default, which means showing the treeview before expanding.. so i need to save the treeview state in order to remain the treeview state. i had tried the below method but it's not working, anyone can help..
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadTransactionMenu();
if (Session["ExpandedNodes"] != null)
((List<string>)Session["ExpandedNodes"]).ForEach(a => TreeView1.FindNode(a).Expanded = true);
}
}
private void LoadTransactionMenu()
{
//TRANSACTION MENU
string SubModuleID, SubModuleNM, DocModuleID, DocModuleName, MenuTransID, MenuTransName;
SqlConnection con = new SqlConnection(ConString);
string CmdString = "SELECT SUBMODULEID, SUBMODULENM, URLNAME FROM SUBMODULE";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
TreeNode node1 = new TreeNode();
node1.Text = "TRANSACTION MENU";
TreeView1.Nodes.Add(node1);
for (int i = 0; i < dt.Rows.Count; i++)
{
SubModuleID = dt.Rows[i]["SUBMODULEID"].ToString();
SubModuleNM = dt.Rows[i]["SUBMODULENM"].ToString();
TreeNode SubModuleNode = new TreeNode(SubModuleNM, SubModuleID);
SubModuleNode.NavigateUrl = dt.Rows[i]["URLNAME"].ToString();
node1.ChildNodes.Add(SubModuleNode);
CmdString = "SELECT DDID, DOCNAME, DDADDRESS FROM DOCMODULE WHERE SUBMODULEID=#SUBMODULEID";
cmd = new SqlCommand(CmdString, con);
cmd.Parameters.AddWithValue("#SUBMODULEID", SubModuleID);
sda = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
sda.Fill(dt2);
for (int j = 0; j < dt2.Rows.Count; j++)
{
DocModuleID = dt2.Rows[j]["DDID"].ToString();
DocModuleName = dt2.Rows[j]["DOCNAME"].ToString();
TreeNode DocModuleNode = new TreeNode(DocModuleName, DocModuleID);
DocModuleNode.NavigateUrl = dt2.Rows[j]["DDADDRESS"].ToString();
SubModuleNode.ChildNodes.Add(DocModuleNode);
CmdString = "SELECT DID, DNAME, DADDRESS FROM MENUTRANSACTION WHERE DDID=#DDID AND UID= '" + Session["UserID"] + "'";
cmd = new SqlCommand(CmdString, con);
cmd.Parameters.AddWithValue("#DDID", DocModuleID);
sda = new SqlDataAdapter(cmd);
DataTable dt3 = new DataTable();
sda.Fill(dt3);
for (int k = 0; k < dt3.Rows.Count; k++)
{
MenuTransID = dt3.Rows[k]["DID"].ToString();
MenuTransName = dt3.Rows[k]["DNAME"].ToString();
TreeNode MenuTransNode = new TreeNode(MenuTransName, MenuTransID);
MenuTransNode.NavigateUrl = dt3.Rows[k]["DADDRESS"].ToString();
DocModuleNode.ChildNodes.Add(MenuTransNode);
}
if (DocModuleNode.ChildNodes.Count == 0)
{
SubModuleNode.ChildNodes.Remove(DocModuleNode);
}
}
if (SubModuleNode.ChildNodes.Count == 0)
{
node1.ChildNodes.Remove(SubModuleNode);
}
}
}
public void GetExpandedStatus(TreeNode node, List<string> ExpandedNodes)
{
//check if node is expanded
if (node.Expanded.GetValueOrDefault(false))
ExpandedNodes.Add(node.ValuePath);
node.ChildNodes.Cast<TreeNode>().ToList().ForEach(a => GetExpandedStatus(a, ExpandedNodes));
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
List<string> expandedNodes = new List<string>();
//get all expanded nodes
TreeView1.Nodes.Cast<TreeNode>().ToList().ForEach(a => GetExpandedStatus(a, expandedNodes));
//collapse all to reset the treeview
TreeView1.CollapseAll();
//save expanded node value paths
Session["ExpandedNodes"] = expandedNodes;
}

How to add 2nd input on the KeyPress Function?

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

How can I show 2 columns in a combobox? (multiple values)

Right now I have this:
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"]);
}
Now it only shows the klantId, but I also want to show the name. And when I've that, so the klantId and the name how can I only select the klantId when I say:
selectedUserId = combobox.Text;
EDIT:
//THIS IS WHERE I INITIALISE THE COMBOBOX
da = new SqlDataAdapter("SELECT (kg.voornaam+' '+kg.achternaam + ' - ' + CONVERT(varchar,l.klantId)) AS dispValue FROM LOGIN l inner join klantGegevens kg on l.klantId=kg.klantid WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
//THIS IS THE BUTTON FOR DELETING A USER
private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (userInformation.addPersonsPermission)
{
int selectedUserId = Convert.ToInt32(((DataRowView)txtKlantid.SelectedValue)["klantId"]);
if (users.deleteKlantAdmin(selectedUserId))
{
MetroMessageBox.Show(this, "Gebruiker "+selectedUserId+" is verwijderd", "Verwijderd");
}
else
{
MetroMessageBox.Show(this, "Er ging iets fout, contacteer de beheerder", "Fout");
}
}
else
{
loginAddUser addUserLogin = new loginAddUser();
addUserLogin.ShowDialog();
}
}
You can use DisplayMember and ValueMember property of ComboBox
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "Name"; //Name of field to display
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
And you can get Name And Id back by following
var name = txtKlantid.Text;
var id = txtKlantid.SelectedValue;
As per your requirement you can combine Id and Name
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"].ToString()+"-"+dtt.Rows[i]["Name"].ToString());
}
DisplayMember and ValueMember properties will be your friends in this case.
Please avoid selecting all the fields from the table just to fill your combobox. You can just do something like,
da = new SqlDataAdapter("SELECT (name + ' - ' + CONVERT(varchar,klantId)) AS dispValue, klantId FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
In this example, txtKlantid.SelectedValue will give you the klantId values and txtKlantid.Text will give you the name - klantId values.
Hope this helps...

how to display comparison chart using ajax

I am trying to display ajax bar chart in my web page. But it is only displaying one value .
My db contains 3 columns(name, credit, debit) I want to display the credit debit values in chart. But the chart is only displaying one value. How can I modify the given below coding. Thank you.
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select Name from aTable";
DataTable dt = GetData(query);
ddlCountries.DataSource = dt;
ddlCountries.DataTextField = "Name";
ddlCountries.DataValueField = "Name";
ddlCountries.DataBind();
ddlCountries.Items.Insert(0, new ListItem("Select", ""));
}
}
private DataTable GetData(string query, SqlParameter[] prms = null)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["demoConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
if (prms != null)
cmd.Parameters.AddRange(prms);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
string query = "select Name, Debit, Credit From aTable where Name=#Name";
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#name", SqlDbType.NVarChar);
prms[0].Value = ddlCountries.SelectedItem.Value.ToString();
DataTable dt = GetData(query, prms);
string[] x = new string[dt.Rows.Count];
decimal[] y = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
x[i] = dt.Rows[i][0].ToString();
y[i] = Convert.ToInt32(dt.Rows[i][1]);
}
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
BarChart1.CategoriesAxis = string.Join(",", x);
BarChart1.ChartTitle = string.Format("{0} -RunTimeReportChart", ddlCountries.SelectedItem.Value);
if (x.Length > 3)
{
BarChart1.ChartWidth = (x.Length * 100).ToString();
}
BarChart1.Visible = ddlCountries.SelectedItem.Value != "";
}
Data Base:
Actual Output:
The given below chart is only displaying the name and debit value. I want to display the credit value also. Please help me.
Something Like :
decimal[] z = new decimal[dt.Rows.Count];
z[i] = Convert.ToInt32(dt.Rows[i][2]);
BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = z });

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 ;
}

Categories

Resources