I had done till one last part. Unsure how or what should I do to add into code.
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//What should i put here
gv.DataBind();
}
I created the table and the view, got the query and fill it in to the table (if I am not wrong). Is it completed or is thing else I should do to ensure it is in the gridview so I can display them out.
Any help will be good, thank you guys
Just Put :
gv.DataSource=dt;
in place of What should i put here to bind datatable data to gridview
So after you fill the result in your data table
Make dt the gridview datasource.
//put it in the gridview datasource.
gv.DataSource = dt;
You can refer to this MSDN page for setting gridview datasource
To complete your code:
public String DisplaySheetList()
{
DataTable dt = new DataTable();
GridView gv = new GridView();
string sqlStatement1 = "SELECT cs.SheetId AS sheet_id, ltm.LocationType AS location_type, cs.PalletNo AS palletNo, cs.period AS period,cs.syncDate AS syncDate,cs.syncStatus AS syncStatus "
+ "FROM CountSheet cs JOIN LocationTypeMaster ltm ON ltm.LocationId = cs.LocationId " +
" ORDER BY 1 DESC";
SqlCommand sqlCmd1 = new SqlCommand(sqlStatement1, conn);
SqlDataAdapter sqlDa1 = new SqlDataAdapter(sqlCmd1);
sqlDa1.Fill(dt);
//put it in the gridview datasource.
gv.DataSource = dt;
gv.DataBind();
}
Related
GridView1 does not display the data that the SQL statement brings
as :
.....{statements to select attributes and conditions to putting SQL statement}
(Example on SQL :SELECT [patient].name_patient FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime AND [patient].gender_patient = 'Male')
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
con.Open();
string q_sql = "SELECT " + slct + " FROM patient, visitFACTABLE, datetime, disease WHERE [patient].Id_patient = [visitFACTABLE].Id AND [visitFACTABLE].Id = [datetime].Id_datetime " + w;SqlDataAdapter da = new SqlDataAdapter(q_sql, con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
trigger debugger break point # GridView1.DataSource = dt;
then hover visualize 🔎 and check did your dt ( data table) contain at least 1 row . if got row , by right your Gridview shall show data
So I have a dropdown list that is being populate from database, the goal is to get the selected values from the dropdown list and put in the gridview. The problem is it only adds one row and only updates that row when I try to select new values from the dropdownlist.
I have tried doing Datarow row = dt.newrow() but not luck
Back End code of button click
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM Product_Details WHERE Model = '" + ddlModel.SelectedItem.Text + "' AND Price = '" +ddlPrice.SelectedItem.Text + "'", con);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
First image when I select values from dropdown list for first time
Second image is when I select new values from dropdown list but it updates previous table and does not add new row in gridview
On Add Button click you are retrieving new data from database and creating new datatable that's why you are loosing the previously selected data.
You need to maintain the previously retrieved data between two clicks on Add button.
You need to create a separate DataTable in aspx.cs and store it in the ViewState and add new row to that table on button click and re-bind it to the GridView.
You need to write following code to achieve this.
//This method will check if the table exist in the ViewState
//If table does not exist in ViewState, a new table will be created and stored in ViewState
private DataTable GetDataTable()
{
DataTable dt = ViewState["SelectedModels"] as DataTable;
if (dt == null)
{
dt = new DataTable();
dt.TableName = "ColorData";
dt.Columns.Add(new DataColumn("Model", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(string)));
ViewState["SelectedModels"] = dt;
}
return dt;
}
//This method will store DataTable to ViewState
private void SaveDataTable(DataTable dataTable)
{
ViewState["SelectedModels"] = dataTable;
}
//This method will get the data from the database, add it to the DataTable
//And it will re-bind the DataTable to the GridView and store the updated DataTable to ViewState
private void AddItemToList(string modelName, string price)
{
string CS = ConfigurationManager.ConnectionStrings["POS_SystemConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd =
new SqlCommand("SELECT * FROM Product_Details WHERE Model = #modelName AND Price = #price", con))
{
var modelParameter = new SqlParameter();
modelParameter.ParameterName = "#modelName";
modelParameter.Value = modelName;
cmd.Parameters.Add(modelParameter);
var priceParameter = new SqlParameter();
priceParameter.ParameterName = "#price";
priceParameter.Value = price;
cmd.Parameters.Add(priceParameter);
con.Open();
using (var sqlReader = cmd.ExecuteReader())
{
var dataTable = GetDataTable();
while (sqlReader.Read())
{
var dataRow = dataTable.NewRow();
//Hear I assume that Product_Details table has Model and Price columns
//So that sqlReader["Model"] and sqlReader["Price"] will not have any issue.
dataRow["Model"] = sqlReader["Model"];
dataRow["Price"] = sqlReader["Price"];
dataTable.Rows.Add(dataRow);
}
SaveDataTable(dataTable);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
}
}
}
And now the Click Event Handler of the button should call the above method as following.
protected void bttnAdd_Click(object sender, EventArgs e)
{
AddItemToList(ddlModel.SelectedItem.Text, ddlPrice.SelectedItem.Text);
}
This should help you resolve your issue.
SqlConnection con = new SqlConnection(connectionString: ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
String cquery = "SELECT cart.ProductID, ProName, Size, Colour, Price FROM cart, Products WHERE Custid=" + Session[custid] + "AND Products.ProductID = cart.ProductID";
SqlCommand ccmd = new SqlCommand(cquery, con);
DataTable dataTable = new DataTable();
CRepeater.DataSource = ccmd.ExecuteReader();
CRepeater.DataBind();
con.Close();
DataRow[] dr = dataTable.Select("SUM(Price)");
Label3.Text = Convert.ToString(dr[0]); ;
I am using a repeater to display data from database and i cant seem to figure out how to get the sum using repeater
Best approach to calculate the sum of a column in a DataTable use the DataTable.Compute method.
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Price)", "");
Display the result in your Total Amount Label like so:
Label3.Text = sumObject.ToString();
Update
your missing to load the DataTable,try this
var dataReader = ccmd.ExecuteReader();
var dataTable = new DataTable();
dataTable.Load(dataReader);
CRepeater.DataSource = dataTable;
CRepeater.DataBind();
I have a combobox with items. I want to get a value from database and show the value in the combobox as the selected item. But it should also display items.
I tried to use combobox.selectedvalue. But it's not working.What should I do?
SqlDataAdapter komut = new SqlDataAdapter("select * from Ogrenci where ogr_no= '" +
Convert.ToInt32(a) + "' ", baglanti);
DataTable dt = new DataTable();
komut.Fill(dt);
DataRow drw1 = dt.Rows[0];
string ogretim = drw1["ogretim"].ToString();
//comboBox7.SelectedItem = comboBox7.FindString(ogretim);
comboBox7.SelectedValue = ogretim;
Try this:
comboBox7.Items.FindByValue(ogretim).Selected = true;
I have the following code which doesn't seem to work. In the Page_Load function I populate the DataSet and display the results in a grid view.
newsCommand = new SqlCommand("SQL code here", dbConnection);
newsDataSet = new DataSet();
newsDataAdapter = new SqlDataAdapter(newsCommand);
newsDataAdapter.SelectCommand = newsCommand;
newsDataAdapter.Fill(newsDataSet, "Bulletins");
if (!Page.IsPostBack)
{
GridViewMain.DataSource = newsDataSet;
GridViewMain.DataBind();
}
I have some links which call this function to filter the data (yearID is passed as a parameter):
DataTable newsTable = new DataTable();
newsTable = newsDataSet.Tables[0];
DataView dvData = new DataView(newsTable);
dvData.RowFilter = "Year > '" + yearID + "'";
GridViewMain.DataSource = dvData;
GridViewMain.DataBind();
Yet the gridview shows the data it orignally loaded, and not the filtered data. The only thing I can think of is that I'm not using the DataTable in the Page_Load function. What else am I missing?
Thanks,
Adrian
Changed the code in the function to:
DataView dataView = newsDataSet.Tables[0].DefaultView;
dataView.RowFilter = "NewsDate2 Like '%" + yearID + "'";
GridViewMain.DataSource = dataView;
GridViewMain.DataBind();
It must have been something in the RowFilter statement.
Filter data from DataTable and display it in Gridview.
string category = ddlcat.SelectedItem.Value; // this can be any input by user
DataTable dt = filter_dt; //filter_dt is DataTable object, contains actual data, from there we will filter
DataView dataView = dt.DefaultView;
if (!string.IsNullOrEmpty(category))
{
dataView.RowFilter = "Category = '" + category + "'";
}
Gridview1.DataSource = dataView;
Gridview1.DataBind();
If any doubt,feel free to ask.
Thank you