Populate GridView - c#

I cant populate grid view with the data sent to api. tell me where is the flaw. I have no idea.
protected void btnGo_Click(object sender, EventArgs e)
{
WSmyWebAPI.myWeb wsAPI = new WSmyWebAPI.myWeb();
WSmyWebAPI.OrderSearchParameters sSearchParameters = new
WSmyWebAPI.OrderSearchParameters();
DataSet ds = new DataSet();
DateTime dtmStartDate;
DateTime dtmEndDate;
dtmStartDate = Convert.ToDateTime(dpApproved.Text);
dtmEndDate = Convert.ToDateTime(dpShipped.Text);
oid = txtOrderID.Text;
opid = txtPartID.Text;
sSearchParameters.StartDate = dtmStartDate;
sSearchParameters.EndDate = dtmEndDate;
sSearchParameters.OrderID = oid;
sSearchParameters.OrderPartID = opid;
ds = wsAPI.OrderSearch(sSearchParameters);
GridView1.DataSource = ds;
GridView1.DataBind();
}

Following is a sample code. You may manipulate or adjust your code accordingly.
Make sure you have aspx code in place as well. That means the columns you want to display. Try to add
GridView1.Vissible = True
Further make sure to add a try catch block and check on SqlException. Try to go on line by line debug mode. I would suggest to display the error on a label in the webpage until your entire page is bug free. So you know where and what went wrong.
As for a suggestion, it's better to take out the connection , query parameter portion out Go click event. Add a separate method to do that. Only get the data set or data table (I recommend data table) and set it to gridview under Go click event.

Related

Treat a general ASP.NET Control like a list-based control (i.e. DropDownList, RadioButtonList, etc.)

I have built a method that clears and resets a DropDownList with the appropriate data as specified by the user, like so:
protected void ResetDDL(DropDownList ddl, DataTable dt)
{
ddl.Items.Clear();
ddl.DataSource = dt;
ddl.DataBind();
}
private void LoadVehicleTypes()
{
DataTable dt = new DataTable();
SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnectionstring"].ConnectionString);
sc.Open();
SqlDataAdapter sda = new SqlDataAdapter("procedure", sc);
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.Fill(dt);
sc.Close();
ResetDDL(ddlYourDropDown, dt);
}
While this works as well as it should, I noticed that the code to do the same for a RadioButtonList is identical and it made me wonder if there's a way to combine ResetDDL with the RadioButtonList equivalent: ResetRBL. To do this, I tried replacing DropDownList in the code with Control, but this only yielded in a Control does not contain a definition for 'Items/DataSource' error, so I looked to see if there was any way to tell the program that a given Control is a DropDownList or RadioButtonList and what to do with them once they are confirmed to be a DDL or RBL. The idea here is to take the name of one of these controls, find the actual control itself, and execute the reset method.
From here, I ran a test to see if I could get the Control's type -- and I could!
bool itworks = false;
string tst = rbl.GetType().ToString(); // in this case, tst is "System.Web.UI.WebControls.DropDownList"
if (tst.Contains("RadioButtonList"))
itworks = true;
From here I thought getting the control type would be as simple as getting the text out of a Control in a GridView, but this was not the case. I realized that whereas you can easily fetch the GridView's text and put it into a procedure --
foreach (GridViewRow row in gvTempVehicleData.Rows)
{
SqlCommand cmdVData = new SqlCommand("cmdVDataProcedure", sc);
cmdVData.CommandType = CommandType.StoredProcedure;
cmdVData.Parameters.AddWithValue("DataYear", ((TextBox)row.FindControl("txtTempDataYear")).Text);
cmdVData.ExecuteNonQuery();
}
-- it doesn't seem like quite the same can be done for a vehicle outside a GridView. But still I'm wondering: is there a way to take a Control's name as a string, find the actual control of the same name, and use the methods of the control type I'm looking for? If this is possible, I think it could help a bit to chop down the amount of code at my disposal.
Any help at all would be greatly appreciated!
The problem is that the type of control being taken in. Rather than a Control, the method should accept a ListControl like so:
public void ResetList(ListControl control, DataTable newData)
{
control.Items.Clear();
control.DataSource = newData;
control.DataBind();
}

Filter data within datagridview bounded from DataSet

I have bounded data to datagridview from DataSetand I am trying to filter
these bounded data within datagridview on event of textchange
I got two issues when
I start typing it work fine except it delete the custom datagridview headers and set the name of columns query ex. Header is 'First Name' it replaced by 'NAM' which is the column name at database...
Second issue when I came into else part it wont re-bounded and throw an Exception what I have missed ?
public DataSet GetPatientList()
{
string connStr = ConfigurationManager.ConnectionStrings["SRJDconnstr"].ToString();
string cmdStr = #"SELECT ROW_NUMBER()OVER(ORDER BY ID) AS SEQ,
ID,
DocNUM,
NAM,
FNAME,
LFNAME,
PHONE,
MOBILE,
SEX,
BIRTHDAY,
ADDRESS,
ENDATETIME
FROM SICK
ORDER BY ENDATETIME ASC;";
SqlConnection conn = new SqlConnection(connStr);
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.CommandText = cmdStr;
cmd.CommandType = CommandType.Text;
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds, "PatientList");
DGV_PatientList.Columns["DGV_PatientList_RowNum"].DataPropertyName = ds.Tables["PatientList"].Columns["SEQ"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_PatientID"].DataPropertyName = ds.Tables["PatientList"].Columns["ID"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_DocNUM"].DataPropertyName = ds.Tables["PatientList"].Columns["DocNUM"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_FirstName"].DataPropertyName = ds.Tables["PatientList"].Columns["NAM"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_FatherName"].DataPropertyName = ds.Tables["PatientList"].Columns["FNAME"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_LastName"].DataPropertyName = ds.Tables["PatientList"].Columns["LFNAME"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_Phone"].DataPropertyName = ds.Tables["PatientList"].Columns["PHONE"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_Mobile"].DataPropertyName = ds.Tables["PatientList"].Columns["MOBILE"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_Gender"].DataPropertyName = ds.Tables["PatientList"].Columns["SEX"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_Birthday"].DataPropertyName = ds.Tables["PatientList"].Columns["BIRTHDAY"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_Address"].DataPropertyName = ds.Tables["PatientList"].Columns["ADDRESS"].ColumnName;
DGV_PatientList.Columns["DGV_PatientList_EntryDate"].DataPropertyName = ds.Tables["PatientList"].Columns["ENDATETIME"].ColumnName;
return ds;
}
}
Text Change event
private void TB_FirstName_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(TB_FirstName.Text))
{
// first try below
(ds.Tables["PatientList"] as DataTable).DefaultView.RowFilter = string.Format("NAM LIKE '%{0}%'", TB_FirstName.Text);
// second try below
//ds.Tables["PatientList"].DefaultView.RowFilter = string.Format("NAM LIKE '%{0}%'", TB_FirstName.Text);
}
else
{
DGV_PatientList.DataSource = GetPatientList();
DGV_PatientList.DataSource = ds.Tables["PatientList"].DefaultView;
}
}
Set AutoGenerateColumns to false.
That is what is causing the names to change, and also why you are getting the exception. The columns don't exist anymore and you are referencing them by name.
Working with DataGridView bound to a dataset isn't supposed to be this hard - you must have been following a really old, or poorly written tutorial
The way this is all supposed to hang together is much more neat and compact:
//in your code that handles loading the grid with data, e.g. in a Load button handler
patientListTableAdapter.Fill(ds.PatientList); //strongly typed dataset, table is already bound to grid in design time.
//Visual Studio binds it fully for you when you add it to the form, in the designer
//you never again mess with the bindings, just fill and empty the table: MVC
private void TB_FirstName_TextChanged(object sender, EventArgs e){
if(string.IsNullOrWhiteSpace(TB_FirstName.Text)
patientListBindingSource.Filter = null;
else
patientListBindingSource.Filter = string.Format("NAM LIKE '%{0}%'", TB_FirstName.Text);
}
Yes... just 5 lines of code should be doing everything you're trying to achieve here. Right now, you're using these technologies in an incorrect way, and achieving a difficult and poor performing result.
For guidance on how you should be using datatables, refer to MSDN:
https://msdn.microsoft.com/en-us/library/fxsa23t6.aspx
Start with the "Creating a Simple Data Application" walk through, make a new project, follow th steps and create a new sample app. After you've done that, i recommend coming back to the existing app and making NO attempts to salvage what has already been done - delete the lot, remove the datagridview from the form, create a new typed dataset, link it to your DB, drop a new correctly bound datagridview on your form and th designer will set everything up. Then all you need to do is pick a suitable place to load it with data, and apply a textchanged handler (the 5 lines of code I put above)
I know it's going to be hard, throwing away all that code you poured blood weat and tears into.. but it will always be a headache, and never work right, because it's plain up the wrong way to go about working with data and bound controls

What is the best way to return values from another page in code behind in asp.net?

I have two pages. On the first one I have two drop down lists and button like this:
Code for this button is:
protected void btnIzabraniProizvodi_Click(object sender, EventArgs e)
{
Session["Id_Dobavljaca"] = ddlDobavljaci.SelectedValue;
Session["Id_Kategorija"] = ddlKategorija.SelectedValue;
Response.Redirect("IzabraniProizvodi.aspx");
}
When I click on this button the secont page opens.
This two sessions are input parameters for the SQL query. Here is the code on the second page:
protected void Page_Load(object sender, EventArgs e)
{
string idDobavljaca = Session["Id_Dobavljaca"].ToString();
string idKategorija = Session["Id_Kategorija"].ToString();
string konekcioniString = ConfigurationManager.ConnectionStrings["moja_konekcija"].ConnectionString;
using (SqlConnection sqlKonekcija = new SqlConnection(konekcioniString))
{
SqlDataAdapter sqlDA = new SqlDataAdapter("spVratiIzabraneProizvode", sqlKonekcija);
sqlDA.SelectCommand.Parameters.AddWithValue("#Id_dobavljaca", idDobavljaca);
sqlDA.SelectCommand.Parameters.AddWithValue("#Id_kategorija", idKategorija);
sqlDA.SelectCommand.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
sqlDA.Fill(ds);
ds.Tables[0].TableName = "IzabraniProizvodi";
gridView.DataSource = ds.Tables["IzabraniProizvodi"];
gridView.DataBind();
}
}
My question is, when this dataSet is empty how can I get some message on the first page below the button: "No information for this values, try again with different values"? Any idea?
There is no way to do this normally and you have two not good ways:
You can use child and parent page. The second page will be the child of first page and data will send from child to parent by javascript. but the problem is that this does not work in chrome for security reasons.
The second way is to check automatically from first page by ajax method in periods of times.
setInterval(function(){ AJAX-CHECK }, 5000)
If you want each one of those senarios i will more explain.

DataGridView playing stubborn. It just wouldn't bind

I have one stubborn data grid view is refusing to display the bound data.
i placed a grid view named exhibitgridview and set its datasource to none. then i added a standalone data source that can return columns into the grid but first there data displayed in the grid would be based on a what gets selected from a dropdown list. check it out from the picture below.
So basically some item is selected from the dropdown list next to the caseid label and the grid displays values accordingly... AS such i needed a selectedIndexchanged method so i had this in my page.cs
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
CreateDataSet();
caseID = DropDownList1.SelectedItem.Value.Trim();
DataView exhibitDataView = new DataView(exhibitDataSet.Tables[0]);
exhibitDataView.RowFilter = "FilingID = '" + caseID + "' ";
ExhibitGridView.DataSource = exhibitDataView;
ExhibitGridView.DataBind();
}
private void CreateDataSet()
{
exhibitConnection.ConnectionString =
ExhibitListSqlDataSource.ConnectionString;
exhibitSqlDataAdapter.SelectCommand = new
SqlCommand(ExhibitListSqlDataSource.SelectCommand, exhibitConnection);
exhibitSqlDataAdapter.Fill(exhibitDataSet);
}
The code runs sweet...I inserted a breakpoint as to ensure some data is actually returned for binding and there is...you can see that from the screen shot below:
that was until (ExhibitGridView.DataBind()). So when i run the next block, i expect the data to bind and display in the browser but for some unknown reason the gridview is acting stubborn. i tried specifying the datasource directly and it displays successfully at pageload but otherwise it wouldn't respond.
What could be the cause?
I do believe you need to supply your DataAdapter with the parameters that you are supplying your select statement with. Take a look.
I have given you an example from my code which uses OleDB (I have removed all the open / close connection for ease of reading). They are VERY similar.
SqlCmd = "select * from App_Details WHERE App_Name LIKE #Var";
aCommand = new OleDbCommand(SqlCmd, aConnection);
aCommand.Parameters.AddWithValue("#Var", value);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(SqlCmd, aConnection);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(dataAdapter);
// Now I do not see this part in your code right before you bind your data
dataAdapter.SelectCommand.Parameters.AddWithValue("#Var", value);
DataTable table = new DataTable();
dataAdapter.Fill(table);
dgvSearchApp.DataSource = table;
Make sure about Post Back events. Maybe the page is doing two post backs.

Custom dynamically created Menus producing some strange errors

The background is I have a custom control that is a asp:Menu that is linked to an xmldatasource. The xmldatasource is created dynamically depending on the user privies. Here is the load event for the custom control:
protected void Page_Load(object sender, EventArgs e)
{
string userId = (string)Session["userId"];
if (userId != null)
{
DataSet ds = dal.RetrieveApplications(userId);
ds.DataSetName = "Menus";
ds.Tables[0].TableName = "Menu";
DataRelation relation = new DataRelation
("ParentChild",
ds.Tables["Menu"].Columns["Folder_Id"],
ds.Tables["Menu"].Columns["Parent_Folder_ID"], true);
relation.Nested = true;
ds.Relations.Add(relation);
xmlDataSource1.Data = ds.GetXml();
}
}
This works perfectly for the first user that uses it. But it seems that every subsequent user is actually getting the first user's menu. I have walked it through and verified that my dataset is getting created fine and when I examine the XMLDatasource.data at the end of the load the xml is correct.
I am really stuck.
I found the answer and though I would leave it out here for others who might search for this:
But I had to set the "ENABLECACHING" to false on the xmldatasource.

Categories