Web Forms - Multiple Select Query Results in a GridView? - c#

I'm an extreme newbie. Please bear with me.
I'm trying to populate a GridView with multiple resultsets. I'm using a DataSet with mulitple DataTables. This code has only 2 DataTables, but I will need to use more than 5 or maybe 10.
ASP.NET 4.5.1 Web Forms w/ MSSQL
Method
public DataSet GvTest()
{
using (SqlConnection conn = new SqlConnection(strConn))
{
conn.Open();
SqlCommand cmd = new SqlCommand
(
"SELECT s.StudioName, i.Studio, i.UPC, i.Title, i.Price, i.Availability, i.Location, i.Qty " +
"FROM tbl_Item i JOIN tbl_studio s ON i.Studio = s.StudioID WHERE i.Availability = 'T' and i.Qty > 0 ORDER BY i.Location; " +
"SELECT d.UPC, SUM(d.Qty) FROM tbl_PROrderDetail d JOIN tbl_PROrder p ON d.OrderNo = p.OrderNo " +
"WHERE p.Status = 'P' and p.Type = 'P' GROUP BY d.UPC;"
, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
conn.Close();
DataTable dtTest = new DataTable();
ds.Tables[0].Merge(ds.Tables[1]);
dtTest = ds.Tables[0];
return ds;
}
}
Code behind
protected void Page_Load(object sender, EventArgs e)
{
DataModel dm = new DataModel();
DataSet ds = dm.GvTest();
GridBind(ds);
}
private void GridBind(DataSet ds)
{
gvItemList.DataSource = ds.Tables[0];
gvItemList.DataBind();
}
This code just generates the first SELECT result and then the second SELECT result right after.
What I need to do is add a new column to Tables[0], and the result set of Tables[1] fills the new column.
Row count of Tables[0] = 94
Row count of Tables[1] = 6800
I need 94 rows on my GridView, not 6800. UPC is the connection.
Thanks in advance!

Related

How to edit data in search result in c#

I managed to create a code for my edit button and search button. My edit button is functional. It can edit my data in database, my search code is also functional. My problem is to edit data in search results. Like if i search "naruto", my datagridview will filter all the names that has "naruto" on the database. After i choose and doubleclick on the result, all data will reappear to my textbox. But when i edit that data, it doesn't work. Instead, the first data on my database is the one that is changing not the one that i choose. My edit code is working if i don't search any names and don't choose on the search result.
here's my codes. Please HELP...
private void JOGridView_DoubleClick(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select * from JobOrder", con);
if (JOGridView.CurrentCell != null && JOGridView.CurrentCell.Value != null)
{
TBName.Text = JOGridView.SelectedRows[0].Cells[0].Value.ToString();
TBContact.Text = JOGridView.SelectedRows[0].Cells[1].Value.ToString();
CBStatus.Text = JOGridView.SelectedRows[0].Cells[2].Value.ToString();
TBModel.Text = JOGridView.SelectedRows[0].Cells[3].Value.ToString();
TBSerial.Text = JOGridView.SelectedRows[0].Cells[4].Value.ToString();
TBAccess.Text = JOGridView.SelectedRows[0].Cells[5].Value.ToString();
TBRB.Text = JOGridView.SelectedRows[0].Cells[6].Value.ToString();
TBRP.Text = JOGridView.SelectedRows[0].Cells[8].Value.ToString();
TBIT.Text = JOGridView.SelectedRows[0].Cells[10].Value.ToString();
CBRamarks.Text = JOGridView.SelectedRows[0].Cells[11].Value.ToString();
TBCharge.Text = JOGridView.SelectedRows[0].Cells[12].Value.ToString();
TBRELB.Text = JOGridView.SelectedRows[0].Cells[13].Value.ToString();
}
}
private void BTNEdit_Click(object sender, EventArgs e)
{
{
DialogResult dr;
dr = MessageBox.Show("Are you sure you want to Edit this record?", "Update Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM JobOrder", con);
da.Fill(dt);
dt.Rows[JOGridView.CurrentRow.Index].BeginEdit();
dt.Rows[JOGridView.CurrentRow.Index][1] = TBName.Text;
dt.Rows[JOGridView.CurrentRow.Index][2] = TBContact.Text;
dt.Rows[JOGridView.CurrentRow.Index][3] = CBStatus.Text;
dt.Rows[JOGridView.CurrentRow.Index][4] = TBModel.Text;
dt.Rows[JOGridView.CurrentRow.Index][5] = TBSerial.Text;
dt.Rows[JOGridView.CurrentRow.Index][6] = TBAccess.Text;
dt.Rows[JOGridView.CurrentRow.Index][7] = TBRB.Text;
dt.Rows[JOGridView.CurrentRow.Index][8] = DTDR.Text;
dt.Rows[JOGridView.CurrentRow.Index][9] = TBRP.Text;
dt.Rows[JOGridView.CurrentRow.Index][10] = DTDF.Text;
dt.Rows[JOGridView.CurrentRow.Index][11] = TBIT.Text;
dt.Rows[JOGridView.CurrentRow.Index][12] = CBRamarks.Text;
dt.Rows[JOGridView.CurrentRow.Index][13] = TBCharge.Text;
dt.Rows[JOGridView.CurrentRow.Index][14] = TBRELB.Text;
dt.Rows[JOGridView.CurrentRow.Index][15] = DTDR.Text;
dt.Rows[JOGridView.CurrentRow.Index].EndEdit();
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.Update(dt);
displayrecords();
MessageBox.Show("Selected record has been Updated!", "Done Updating ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
clearrecords();
}
}
private void TBSearch_KeyUp(object sender, KeyEventArgs e)
{
if (TBSearch.Text == " ")
{
}
else
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from JobOrder where Name like ('" + TBSearch.Text + "%')";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JOGridView.DataSource = dt;
con.Close();
}
It's hard to be more specific without seeing more of your code, but the core problem is at least in part that you're not using an MVVM (model view viewmodel) or MVC style binding between the query results and the database query.
Here's why you're only updating the first row in the table rather than the selected row
//creates a new table not visible or linked anywhere
DataTable dt = new DataTable();
//gets every record in JobOrder
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM JobOrder", con);
//fills the DataTable dt with all records from JobOrder
da.Fill(dt);
//uses the current index from the items in JOGridView to select a row in the unconnected/unrelated DataTable dt
dt.Rows[JOGridView.CurrentRow.Index].BeginEdit();
dt.Rows[JOGridView.CurrentRow.Index][1] = TBName.Text;
If you want it to work as written, you'll need to use some value from JOGridView.CurrentRow and match it to a row in dt. Then you can build your update query aimed at the correct row.
Ideally instead, you'll re-write the application to use a proper MVVM style binding to do all of the connections for you automatically.

Listbox returns System.Data.DataRowView instead of values

I am doing a project for my school, where I have to make a C# Windows Forms application that lets me interact with my PostgreSQL database. I have made a listbox, which is supposed to get the names of the tables from my database, and when I select these names, data from that table is show in the datagridview object in the form. The problem is, however, all my listbox values are System.Data.DataRowView, and datagridview only displays values from the first table in the list.
The code:
DataTable tabulusaraksts = new DataTable();
DataTable tabula = new DataTable();
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlDataAdapter adapter2 = new NpgsqlDataAdapter();
string tab;
public datubaze()
{
InitializeComponent();
string connectionstring = "Server=localhost;Port=5432;UserId=postgres;Password=students;Database=retrospeles;";
//string connectionstring = String.Format("Server={0};Port={1};" +
// "User Id={2};Password={3};Database={4};",
// serveris.ToString(), port.ToString(), user.ToString(),
// password.ToString(), database.ToString());
NpgsqlConnection ncon = new NpgsqlConnection(connectionstring);
NpgsqlCommand listfill = new NpgsqlCommand("select table_name from INFORMATION_SCHEMA.tables WHERE table_schema = ANY (current_schemas(false));", ncon);
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.DataSource = tabulusaraksts;
listBox1.DisplayMember = "table_name";
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
}
public void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
tab = listBox1.GetItemText(listBox1.SelectedItem);
adapter2.Fill(tabula);
dataGridView1.DataSource = tabula;
}
That code should work. I tried it with some test data and ListBox was filled with correct values.
To be sure, try to also set ValueMember like
listBox1.DisplayMember = "table_name";
I think the best approach is to add DataTable rows to your ListBox using loop or Linq list. After filling tabulusaraksts iterate through DataRows and add them as items to ListBox, without setting DataSource Something like this (Linq):
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.AddRange(tabulusaraksts.AsEnumerable().Select(row => row[0].ToString()).ToArray());
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;
or, using foreach loop
adapter.SelectCommand = listfill;
adapter.Fill(tabulusaraksts);
listBox1.Items.Clear();
foreach (DataRow row in tabulusaraksts.Rows)
{
listBox1.Items.add(tabulusaraksts[0].ToString());
}
NpgsqlCommand showtable = new NpgsqlCommand("select * from " + tab +";" , ncon);
adapter2.SelectCommand = showtable;

How to print selected row from DataGridView in C# with SQL

Using the following code the first row in SQL is printed only, How can I print selected row from DataGridView in C# with SQL:
public partial class PrintScreen : Form
{
SqlConnection con = new SqlConnection(#"Server = TEST;DataBase=Registration;Integrated Security=true;");
SqlDataAdapter da;
DataTable dt = new DataTable();
public PrintScreen()
{
InitializeComponent();
da = new SqlDataAdapter("select * from data_graduation", con);
da.Fill(dt);
this.dataGridView1.DataSource = dt;
}
private void Print_ys_ar_cert_Click(object sender, EventArgs e)
{
Print_ys_ar_cert frm = new Print_ys_ar_cert();
da = new SqlDataAdapter("select * from data_graduation where ID_gra = '" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'", con);
da.Fill(frm.RegistrationDataSet1.data_graduation);
frm.reportViewer2.RefreshReport();
frm.Show();
}
}
Currently you are passing value of Cells[0] of first row of the grid, you need to pass value of selected row:
if(dataGridView1.SelectedRows.Count>0)
{
var selectedValue = dataGridView1.SelectedRows[0].Cells[0].ToString();
//rest of code
}
Since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report this way:
var row = ((DataRowView)(dataGridView1.SelectedRows[0].DataBoundItem)).Row;
frm.RegistrationDataSet1.data_graduation.Rows.Add(row.ItemArray);
//rest of code

Data grid view not showing data from mysql table

Im trying to get data in data grid view . this code works fine if i use this query :- "Select * from employee.transaction"
But when im trying to put the conditions it does not give any output (just shows a blank table)
My table has month,year column of type Int.Im using mysql server 5.6.25
I cant find the problem with my code.Please help.Thx in advance.
private void load_data_Click(object sender, EventArgs e)
{
string constring = "datasource = localhost;port = 3306;username = ****;password = ****";
MySqlConnection conDataBase = new MySqlConnection(constring);
var cmdDataBase = conDataBase.CreateCommand();
cmdDataBase.CommandText = #"select * from employee.transaction where department = #department AND month = #month AND year = #year";
cmdDataBase.Parameters.AddWithValue("#department", this.department.Text);
cmdDataBase.Parameters.AddWithValue("#month", this.dateTimePicker1.Value.Month);
cmdDataBase.Parameters.AddWithValue("#year", this.dateTimePicker1.Value.Year);
try
{
// here im trying to show table in datagrid view
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
//here im trying to make a excel file which would contain what is currently being displayed in the datagrid view
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
ds.Tables.Add(dbdataset);
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The problem could be, as mentioned by #Bjorn-Roger in the comments, that both 'month' and 'year' are keywords in SQL.
I would suggest you try :
select * from employee.transaction where department = #department AND [month] = #month AND [year] = #year
P.S: Notice the use of [] with the fields 'month' and 'year'.
Edit 1
Also, you might want to check if the date format of the input fields 'month' and 'year' is same as that of database table fields.

The data source does not support server-side data paging. .toList() is not working

I'm trying to load some data from a database, and to filter them using this method.
Now, i want also to show them by pages, especially at the non-filtered part.
I used a DataAdaptor to fill up a dataset table, on which I'm making my filtering.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
OracleConnection con = new OracleConnection(CS);
string query = "select * from table1";
OracleDataAdapter dataAdapter = new OracleDataAdapter(query, con);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "mytbl");
Session["DATASET"] = dataSet;
GridView1.DataSource = from dataRow in dataSet.Tables["mytbl"].AsEnumerable()
orderby dataRow["ID"]
select new guards
{
ID = Convert.ToInt32(dataRow["ID"]),
Nume = dataRow["NUME"].ToString()
};
GridView1.AllowPaging = true;
GridView1.DataBind();
}
You will have to tell ASP.NET how to page. in this case it is .Skip().Take()

Categories

Resources