i'm trying to bind a search textBox ( that uses a Stored Procedure ) with a grid view but when ever i run them and type the search condition ,no results are displayed and the GridView it self dosent show . i tried many ways including using a DataAdapter & DataSet to fill the results of the search textBox and then bind the DataSet to the GridView. but it didnt work either here is the code:
protected void SearchButton_Click(object sender, EventArgs e)
try
{
string con_str = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(con_str);
SqlCommand com = new SqlCommand("dbo.SearchRecords", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter pDocumentTitle = new SqlParameter("#Doc_Title", SearchTextBox.Text);
SqlParameter pUserID = new SqlParameter("#User_ID", SearchTextBox.Text);
SqlParameter pDocumentType = new SqlParameter("#Doc_Type", SearchTextBox.Text);
SqlParameter pDocumentDescription = new SqlParameter("#Doc_Description",SearchTextBox.Text);
com.Parameters.Add(pDocumentTitle);
com.Parameters.Add(pUserID);
com.Parameters.Add(pDocumentType);
com.Parameters.Add(pDocumentDescription);
con.Open();
SqlDataAdapter DA = new SqlDataAdapter(com);
com.ExecuteNonQuery();
DataSet t = new DataSet();
DA.Fill(t);
GridView1.DataBind();
GridView1.DataSource = t;
}
catch (Exception ex)
{
Label2.Text = ex.Message;
//throw;
}
}
I could be wrong but don't you need to call DataBind() after you have set the DataSource property? e.g.
GridView1.DataSource = t;
GridView1.DataBind();
You should change the order of binding as follow...Always write DataBind() after assigning the DataSource to Any DataControl
GridView1.DataSource = t;
GridView1.DataBind();
datasource must define first ,then do the binding
GridView1.DataSource = t;
GridView1.DataBind();
Related
Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :
<asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
</asp:DropDownList>
and is binded as below :
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
I am not able to set a value in the dropdownlist though.Here is what I have done :
private void ExtractData()
{
string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :
protected void ddlGender_DataBound(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
Now it doesnt throw any error and it doesnt select the value as well.
PS : 1.I have set Autopostback true for the ddl.
2.I am aware of sqlInjection and have made changes to make it look simpler.
My final PageLoad looks like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
ExtractData();
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
}
if (hfImagePath.Value == "" || hfImagePath.Value == "0")
{
imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
hfImagePath.Value = "0";
}
else
{
imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
}
//lblRegistration.Text = Session["Button"].ToString();
}
For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.
Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.
I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).
Try changing:
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
To:
ddlGender.SelectedValue = rdr["Gender"].ToString();
Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
You are trying to set the value to a specific Column, yet you are binding it to a DataSet and not a DataTable. (A DataSet has no columns only DataTables).
Try the following assuming the DataSet has a table returned and the column names match your table structure:
string strDesiredSelection = "Male";
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds.Tables[0];
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
foreach(ListItem li in ddlGender.Items){
if(li.Value.Equals(strDesiredSelection)){
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(li);
}
}
Well As the title explains it all so here is the code i used so far
public partial class data : System.Web.UI.Page
{
System.Data.SqlClient.SqlConnection con3;
System.Data.SqlClient.SqlDataAdapter da;
DataSet ds1;
DataTable dt;
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
con3 = new System.Data.SqlClient.SqlConnection();
con3.ConnectionString="Data Source=localhost; initial catalog=test;user id=xx;password=xxxx;";
con3.Open();
ds1 = new DataSet();
SqlCommand cmd3 = new SqlCommand();
cmd3.CommandType = CommandType.StoredProcedure;
cmd3.CommandText = "selectdata";
cmd3.Connection = con3;
da = new SqlDataAdapter (cmd3);
da.Fill(ds1, "abc");
con3.Close();
dt = new DataTable();
dt = ds1.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
Stored Procedure is
Create PROCEDURE [dbo].[selectdata]
AS
BEGIN
select * from data
END
i searched stack overflow & did search on Google but nothing happened.
i tried closing connection after data bind, defining a new data set & creating the table again & much more please help
Try reloading the page after insertion.
The Answer Above just refresh the page so in my view it should be
1--> Define A Function & bind data in this such as
private void bind_data()
{
ASPxGridLookup2.DataSource = dt_employee;
ASPxGridLookup2.DataBind();
ASPxGridLookup3.DataSource = dt_attendance;
ASPxGridLookup3.DataBind();
ASPxGridView1.DataSource = dt_attendance;
ASPxGridView1.DataBind();
}
2--> Call this function whenever you need to refresh the datagrid such as right after insertion
obj2.insertion();
bind_data();
i test my query in sql server and it's working 100%
but in my page not work !!
this my query
UPDATE Employee SET
Name='jojo',
Age=19,
GenderID=2,
CountryID=5,
Mobile=0917021092
WHERE EmployeeID=10
this my code
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEditID");
Label EmployeeID = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEmployeeID");
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
DropDownList gender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropGender");
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropCountry");
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
string stringconnectiong = ConfigurationManager.ConnectionStrings["Employee_TestConnectionString"].ConnectionString;
string sql = "update Employee set Name=#Name, Age=#Age,GenderID=#GenderID , CountryID=#CountryID , Mobile=#Mobile where EmployeeID=#EmployeeID AND ID=#ID";
SqlConnection con = new SqlConnection(stringconnectiong);
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID.Text);
cmd.Parameters.AddWithValue("#ID", id.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#Age", age.Text);
cmd.Parameters.AddWithValue("#GenderID", gender.SelectedValue);
cmd.Parameters.AddWithValue("#CountryID", country.SelectedValue);
cmd.Parameters.AddWithValue("#Mobile", mobile.Text);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dr.Fill(ds);
GridView1.DataSource = ds;
GridView1.EditIndex = -1;
BindGridview();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Error Updating ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
con.Dispose();
BindGridview();
}
}
Since your datasource is a dataset, you need to specify which data table within the dataset you are using via the DataMember propery. Or just use a data table as your datasource.
Replace the dataset lines with the following:
DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;
In addition, use the GridView1_RowUpdated event. The GridView1_RowUpdating event is fired before the table is updated, therefore your parameter values have not been updated yet.
In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}
I am using asp.net 2008 repeater control. I am trying to refresh the repeater control when a button is clicked, it shows me duplicated values, that means its appending the same values once again. Here is my code
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlServerConnection"].ConnectionString);
String sql;
sql = "select * from FeeCollection Where AdminNo='"+lblstano.Text+"'";
cmd = new SqlCommand(sql, con);
da = new SqlDataAdapter(sql, con);
da.Fill(ds, "FeeCollection");
dt = ds.Tables["FeeCollection"];
Repeater4.DataSource = dt;
Repeater4.DataBind();
con.Close();
}
protected void btnMedical_Click(object sender, EventArgs e)
{
LoadRepeater1();
}
I want to remove the existing data and refresh the data instead of appending.
Not sure where ds (DataSet) in instantiated. Try to instantiate the DataSet/DataTable within the LoadRepeater1() method.
public void LoadRepeater1()
{
con = new SqlConnection(ConfigurationManager
.ConnectionStrings["SqlServerConnection"].ConnectionString);
sql = "select * from FeeCollection Where AdminNo=#AdminNo";
cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#AdminNo",System.Data.SqlDbType.VarChar,20).Value=lblstano.Text;
da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
Repeater4.DataSource = dt;
Repeater4.DataBind();
}