Datagridview only adding 1 row - c#

Im trying to add all my users accounts to a gridview but when using the foreach code it is only adding the last value of the datagridview. Is there a way to do all of them?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}

The DataSource property of a DataGridView object shouldn't be one row, but many.
So you can change your code to create a list first and apply this as the DataSource, OR you use the following method:
dataGridView1.Rows.Add(GetResultsTable(row2["username"].ToString());
In the foreach loop.
Hope it helps you out :).

you can use one method to load the data
public DataTable fillDataTable()
{
// select all the columns with expected column name, here I only added 3 columns
string query = "SELECT username as Username, motto as Motto, mail as Email FROM users;
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
set the grid DataSource like below
dataGridView1.DataSource =fillDataTable();

Related

How to split string and write them in different row in same datagridview c#

I have a database which include my computer's ids,users,old users etc.I fill my dataview perfectly.In my db I have a olduser column and it's look like ;
john;marry;tonny
And my other column "date" looks like ;
02.10.2018;05.09.2017;30.08.2015
So I want to see my datagridview like
PCNAME ID USER OLDUSER PLACE DATE
computer1 1 herry spain
computer1 1 john spain 02.10.2018
computer1 1 marry spain 05.09.2017
computer1 1 tonny spain 30.08.2015
When I write the code below it always give me
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
error
int i = 0;
public void firstdatagrid()
{
DataTable table = new DataTable();
dataGridView1.DataSource = table;
baglantı = new SqlConnection();
baglantı.ConnectionString = "Server=asdas;Database=asdsa;User Id=asdsa;password=asdaassad";
baglantı.Open();
komut = new SqlDataAdapter("SELECT * FROM TABLE WHERE PCID= '" + pcidcmbx.Text + "'", baglantı);
ds = new System.Data.DataSet();
komut.Fill(ds, "TABLE");
dataGridView2.DataSource = ds.Tables[0];
dataGridView2.Columns[0].HeaderText = "PCNAME";
dataGridView2.Columns[1].HeaderText = "ID";
dataGridView2.Columns[2].HeaderText = "USER";
dataGridView2.Columns[3].HeaderText = "OLD USER";
dataGridView2.Columns[4].HeaderText = "PLACE";
dataGridView2.Columns[5].HeaderText = "DATE";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
names += row.Cells[3].Value;
dates += row.Cells[5].Value;
dataGridView2.Rows[0].Cells[3].Value = "";
dataGridView2.Rows[0].Cells[5].Value = "";
}
foreach (var a in names.Split(new char[] { ';' }))
{
MessageBox.Show(a.ToString());
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i].Cells[3].Value = a.ToString();
i = i + 1;
}
}
First of all you get this message because your values comes from db and when you try to add a new row manually,datagridview doesn't know what is come.
DataTable table = new DataTable();
DataGridView1.DataSource = table;
So try to use it will fix your problem I guess
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);

How I can change rows places in datadridview?

Good afternoon, dear developers.
Faced such a problem:
there is DataGridVev, I have data lines in it. Depending on the toss-up, I need to sort the order of the rows in the display.
How can I do that?
As I understand the lines do not have an index, and the columns have.
Here is my code for sorting
for(int i = 0; i < 9; i++)
{
int tmp = i;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[2].Value == position[i])
{
Console.WriteLine(position[i] + "Место: " + tmp);
tmp += 9;
}
}
}
copied from the comment of the OP:
con = new SqlConnection();
con.ConnectionString = getConn;
con.Open();
adap = new SqlDataAdapter("SELECT * FROM " + table_name + " WHERE Groupe_year = #year ", con);
string year = comboBox1.Text;
adap.SelectCommand.Parameters.AddWithValue("#year", year);
ds = new System.Data.DataSet();
adap.Fill(ds, "Fighters_Details");
dataGridView1.DataSource = ds.Tables[0];
Assign the Data Source to a Data View instead.
dataGridView1.DataSource = ds.Tables[0].DefaultView;
For Sorting on the Groupe_year column as an example:
((System.Data.DataView)dataGridView1.DataSource).Sort = "Groupe_year";

How do you get the Id of the item in CheckListBox

I have a checkListBox in my windows form application and binded with my database data with SQL. I populate a list of item according to what I select from my comboBox. If I select item 1 from my comboBox, it will display customers' name who is using this item. I want get customers' id according to what I check in my checkListBox.
Here is how I fill my comboBox
private void fill_comboBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
string query = "select itemId, itemName from item_detail";
SqlDataAdapter da = new SqlDataAdapter();
myConn.Open();
DataTable dt = new DataTable();
SqlCommand command = new SqlCommand(query, myConn);
SqlDataReader reader = command.ExecuteReader();
dt.Load(reader);
DataRow dr;
dr= dt.NewRow();
dr.ItemArray = new object[] { 0, "<----------Select an item-------> " };
dt.Rows.InsertAt(dr, 0);
itemComboBox.DataSource = dr;
itemComboBox.ValueMember = "itemId";
itemComboBox.DisplayMember = "itemName";
fill_customerCheckListBox();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is how I fill my checkListBox
private void fill_customerCheckListBox()
{
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
try
{
myConn.Open();
DataSet myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
string commandString = "select fullName from[customer_detail] as cd LEFT JOIN[item_customer] as ic ON ic.customerId= cd.customerI WHERE ic.itemId= '" + itemCombBox.SelectedValue + "' ";
myCommand = new SqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = commandString;
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = myCommand;
myDataAdapter.TableMappings.Add("Table", "customer_detail");
myDataAdapter.Fill(myDataSet);
DataTable myDataTable = myDataSet.Tables[0];
customerCB.Items.Clear();
string s = "Select All Customer";
customer.Items.Add(s);
foreach (DataRow dataRow in myDataTable.Rows)
{
customerCB.Items.Add(dataRow["fullName"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a praremter for loop that trying to loop through every checked item from my customerCB, but this isn't working. When I am in my debug mode, the code DataRow row = (itemChecked as DataRowView).Row; is causing an exception
Object reference is not set to an instance of an object.
I have no idea how to fix this. Help will be appreciated, thanks
string parameterList = "";
foreach (object itemChecked in customerCB.CheckedItems)
{
DataRow row = (itemChecked as DataRowView).Row;
parameterList += (parameterList.Length == 0) ? row[0].ToString() : ", " + row[0].ToString();
}
Try the Following way !!
foreach(object itemChecked in checkedListBox1.CheckedItems)
{
DataRowView castedItem = itemChecked as DataRowView;
string fullName= castedItem["fullName"];
}
(OR) You would need to cast or parse the items to their strongly typed equivalents, or use the System.Data.DataSetExtensions namespace to use the DataRowExtensions.Field method demonstrated below:
foreach (var item in checkedListBox1.CheckedItems)
{
var row = (itemChecked as DataRowView).Row;
int id = row.Field<int>("ID");
string name = row.Field<string>("fullName");
}
it seems than when you are populating your combobox your are entering dataRow["fullName"] therefore this cast DataRow row = (itemChecked as DataRowView).Row won't work as itemChecked only contains the value of fullName and not the row, try adding the dataRow instead.

Datagridview foreach

I coded this for my code what im trying to do is for each of the accounts made in a database it adds it to the datagridviewi tried this code but all the comums are empty?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
public frmMain()
{
this.InitializeComponent();
this.SetupBackstageContent();
ribbonControl1.SelectedRibbonTabItem = ribbonTabItem1;
ribbonTabItem2.Text = "&USER CONTROL";
ribbonTabItem4.Text = "&ADD ONS";
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
}
Your way is wrong,if you want fill dataGrid with all user records just consider this code:
using (SqlConnection conn = new SqlConnection("your connection string"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM users", conn);
DataSet ds = new DataSet();
da.Fill(ds);
dataGridView1.DataSource = ds;
}
Conn();
int i = 0;
cmd = new SqlCommand("select * from tbl_Emp", con);
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
if (Dgv_Emp.Rows.Count > 0)
{ Dgv_Emp.Rows.Clear(); }
Dgv_Emp.Rows.Add(dt.Rows.Count);
foreach (DataRow rw in dt.Rows)
{
Dgv_Emp.Rows[i].Cells[0].Value = rw["Emp_id"].ToString();
Dgv_Emp.Rows[i].Cells[1].Value = rw["Emp_name"].ToString();
Dgv_Emp.Rows[i].Cells[2].Value = rw["Emp_desg"].ToString();
Dgv_Emp.Rows[i].Cells[3].Value = rw["Emp_dept"].ToString();
Dgv_Emp.Rows[i].Cells[4].Value = rw["Emp_gender"].ToString();
Dgv_Emp.Rows[i].Cells[5].Value = rw["Emp_contact"].ToString();
i = i + 1;
}
}
Please use following code:
public DataTable GetResultsTable()
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataTable _userTable = client.ExecuteQueryTable("SELECT * FROM users");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
foreach (DataRow _row in _userTable.Rows)
{
DataRow dr = table.NewRow();
dr["Username"] = "" + _row["username"] + "";
dr["Motto"] = "" + _row["motto"] + "";
dr["Email"] = "" + _row["mail"] + "";
dr["Homeroom"] = "" + _row["home_room"] + "";
dr["Health"] = "" + _row["health"] + "";
dr["Energy"] = "" + _row["energy"] + "";
dr["Age"] = "" + _row["age"] + "";
table.Rows.Add(dr);
}
return table;
}
}
public frmMain()
{
this.InitializeComponent();
this.SetupBackstageContent();
ribbonControl1.SelectedRibbonTabItem = ribbonTabItem1;
ribbonTabItem2.Text = "&USER CONTROL";
ribbonTabItem4.Text = "&ADD ONS";
SqlDatabaseManager.Initialize();
dataGridView1.DataSource = GetResultsTable();
}
Since u r passing DataRow as DataSource for DataGridView view hence only last row would be in datagridview. Here I change ur code and bind DataTable rather than DataRow with DataSource of DataGridView.

C# All rows from MySQL query not going into datagridview

Im trying to fill a DataGridView with the results from a MySql Query however they are not all going in. Here is my code:
try
{
conn.Open();
player_search = new MySqlCommand("SELECT * FROM admin;", conn);
reader = player_search.ExecuteReader();
int counter = 0;
while (reader.Read())
{
player_list[0, counter].Value = reader.GetString(0);
player_list[1, counter].Value = reader.GetString(1);
player_list[2, counter].Value = reader.GetString(6);
player_list[3, counter].Value = reader.GetString(7);
player_list[4, counter].Value = reader.GetString(8);
player_list[5, counter].Value = reader.GetString(9);
player_list[6, counter].Value = "Remove";
counter = counter+1;
}
}
However it doesnt all go in. It only inserts the first row of the query? Why is it doing this? Im getting no errors?
Solved it! I had to do a long winded approach but it works!
MySqlCommand mysqlcmd = new MySqlCommand("SELECT * FROM admin;", conn);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
player_list.DataSource = dt;
int rowIndex = 0;
foreach (DataRow row in dt.Rows)
{
int i = 0;
foreach (var item in row.ItemArray)
{
if (i == 0) {
player_list[0, rowIndex].Value = item.ToString();
}
if (i == 1) {
player_list[1, rowIndex].Value = item.ToString();
}
if (i == 4)
{
player_list[2, rowIndex].Value = item.ToString();
}
if (i == 7)
{
player_list[3, rowIndex].Value = item.ToString();
}
if (i == 8)
{
player_list[4, rowIndex].Value = item.ToString();
}
if (i == 9)
{
player_list[5, rowIndex].Value = item.ToString();
}
player_list[6, rowIndex].Value = "Remove";
++i;
}
++rowIndex;
i = 0;
}
I would suggest you to try to get it using DataSet:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
UPDATE: player_list.DataSource(GetDBDataTable(...));
player_list.DataBind();

Categories