I am hitting a wall with populating a Gridview in ASP.NET CSHTML.
On Page Load, I have this code to initiate data fill.
protected void Page_Load(object sender, EventArgs e)
{
Orisoftds = new DataSet();
using (SqlConnection appCon = new SqlConnection(appdb))
{
SqlDataAdapter orisoftAdapter = new SqlDataAdapter(fillist, appCon);
orisoftAdapter.Fill(Orisoftds, "Staff_List");
}
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
}
With this , the GridView1 will now have a DataSource
On my web page I have these three controls :
In this project , user will have to fill in their ID on the Text box and by clicking the submit button, the GridView will be filled in.
On the submit button, I have these code :
protected void EmpIDSubmit_Click(object sender, EventArgs e)
{
string eID = empIDTextBox.Text;
((DataTable)GridView1.DataSource).DefaultView.RowFilter = "EMPLOYEE_ID = " + eID;
}
Am I missing anything as at the moment when I enter an ID to the textbox, the page will instead just do thing or seems like it refreshed doing nothing.
Is there a difference between filling a Gridview in WinForms and HTML?
Result should contain gridview showing only the user's profile filtered based on their ID given.
You are Missing GridView1.Databind() for DataBind with Gridview,
Please use this line after:
GridView1.DataSource = Orisoftds.Tables["Staff_List"];
I believe you are missing the DataBind method. Try calling GridView1.Databind() in your EmpIDSubmit_Click event.
Answer - I am missing databind.
GridView1.DataBind();
I had a problem where even after databind , the result did not show.
Apparently the submit button has a broken PostBackUrl configuration as i was testing another method earlier.
I deleted my button and replaced with a new one , now results are showing properly.
I no longer need to use a stored procedure method such as :
using (SqlConnection appCon = new SqlConnection(appdb))
{
using (SqlCommand cmd = new SqlCommand("StoredProcedureName", appCon))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EMPLOYEE_ID", empIDTextBox.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Thank you everyone.
Related
I am loading a list of value/text into a asp:dropdownlist by calling a stored procedure. I populate the dropdownlist on the PageLoad method inside a !Page.IsPostBack block like so:
if (!Page.IsPostBack)
{
GetDropDownLists();
DataBind();
}
And this is my code implementation for the backend:
protected void GetDropDownLists()
{
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("get_articletype", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
xArticleTypeList.Items.Clear();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
xArticleTypeList.SelectedIndex = 0;
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
}
If my code isn't inside a !Page.IsPostBack block, after I click my save button the default value will always be the first item of the dropdownlist. But once I put my code inside the !Page.IsPostBack block my dropdownlist is empty. For reference here is the frontend implementation of my asp:dropdownlist.
<asp:DropDownList ID="xArticleTypeList" EnableViewState="true" AutoPostBack="true" CssClass="form-control" runat="server" />
I understand that there are other topics that cover this question, but none of the proposed solutions worked for me. Thanks you in advance for your inputs.
Your problem is that you inserting the blank please select row BEFORE you bind. As a result, when you bind, you are blowing out the drop down.
Try it this way:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand("get_articletype", conn))
{
DataTable dt = new DataTable();
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dt.Load(cmd.ExecuteReader());
xArticleTypeList.DataSource = dt;
xArticleTypeList.DataValueField = "TypeValue";
xArticleTypeList.DataTextField = "TypeName";
xArticleTypeList.DataBind();
xArticleTypeList.Items.Insert(0, new ListItem("- Select.. -", "0"));
}
}
}
And GET RID of your extra call re-bind You have this:
GetDropDownLists();
DataBind(); <--- remove unless you need, or execute BEFORE the GetDropDownList()
So move your add/insert blank row to the drop down to AFTER the drop down data bind.
And REMOVE your DataBind() - you don't need it, and if for some reason you do, then move the DataBind() to before your load of the GetDropDownLists() - but my guess is that you just tossed that in the hope of making this work, and it going to cause the combo box to re-select - so remove unless you give a REALL GOOD HIGH quality outline and narrative as to why you have the DataBin() command there - (but as as noted, if you really, but really really do need to execute that DataBind() command - move it to before the load of the combo).
So, add the blank row after
This button will store what I typed in my textbox into my SQL Server database:
string aOption = Request.Form["option"].ToString();
string ATitle = Request.Form["title"].ToString();
string Adesc = Request.Form["desc"].ToString();
con = new SqlConnection(constr);
con.Open();
cmd = new SqlCommand("INSERT INTO Thread (shareORask, Thread_Title, Thread_Description) VALUES (#shareORask, #Thread_Title, #Thread_Description)", con);
cmd.Parameters.AddWithValue("#shareORask", askORshare_Selected);
cmd.Parameters.AddWithValue("#Thread_Title", AS_Title);
cmd.Parameters.AddWithValue("#Thread_Description", AS_desc);
cmd.ExecuteNonQuery();
con.Close();
Next, I wanted to dynamically generate div and display database content. I did it in Page Load.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Thread", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds;
reptater.DataBind();
con.Close();
}
<asp:Repeater runat="server" ID="reptater">
<ItemTemplate>
<div><%#Eval("Thread_Description") %></div>
</ItemTemplate>
It works but when I submit my input into the textbox. I'm not able to get data shown in the dynamically created. It only works when i refresh the page.
However, duplicate data will be added into my SQL Server database, how do I solve this?
I'm assuming that the button code is in a method called something like MyButton_Click(object sender, EventArgs e).
The button click event is a "Control event" and these happen after the Page_Load event in the page life cycle. To insert into the database during the click event and render the div in one page cycle you would need to render the div in one of the later events, probably the Page_PreRender event.
I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.
After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown();
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
}
protected void FillDropDown()
{
using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);
DataTable dt = new DataTable("Test");
adp.Fill(dt);
ddlVehicleReg.DataValueField = "Id";
ddlVehicleReg.DataTextField = "Value";
ddlVehicleReg.DataSource = dt;
ddlVehicleReg.DataBind();
}
}
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.
I'm sorry for the trivial question, but I cannot find info about this on Google, or in my reference books, which accurately describes/solves my problem.
I have some DropDownList controls on a page, that I am populating with info from a SQL table. When the page is refreshed, the DropDownLists don't lose their old values, but instead get the same values added to them all over again, so now they are double populated. The functionality all still works the same, but it makes the DropDownList controls look less neat and obviously is unwanted.
<asp:DropDownList ID="DropDownList2" runat="server" OnLoad="LoadDutchessSubjects"
AppendDataBoundItems="true">
The LoadDutchessSubjects function in my code behind just grabs all records from the SQL table and loads them into the DDL:
public void LoadDutchessSubjects(object sender, EventArgs e)
{
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM cfhudson_counties ORDER BY County", con);
adapter.Fill(subjects);
DropDownList2.DataSource = subjects;
DropDownList2.DataTextField = "County";
DropDownList2.DataValueField = "County";
DropDownList2.DataBind();
}
catch (Exception ex)
{
DropDownList2.Items.Insert(0, new ListItem("<ERROR: Occured in populating.>", "1"));
}
con.Close();
}
//Overall.Items.Insert(0, new ListItem("<Select Subject>", "0")); //(dev test)
}
Is there something I can do in the Code Behind to prevent this from happening? Does this have to do with ASP.net state and refreshing/what's going on server side? Maybe we can turn this question into a more useful and general explanation of why this is happening in the first place, because I evidently don't understand some important thing about ASP.net here.
do not reload the items on postbacks. they are persisted in viewstate
public void LoadDutchessSubjects(object sender, EventArgs e)
{
if (IsPostback)
return;
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();