I am having a really hard time wrapping my head around the use of datatables. There for i been trying to use them more active, now this is where my issue surface.
This code returns no errors but no data is bound to the repeater:
Page:
<asp:Repeater ID="RepeaterBrand" runat="server">
<ItemTemplate>
<p><%# Eval("products_name")%></p>
</ItemTemplate>
</asp:Repeater>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["brand"] != null && !IsPostBack)
{
var Brand = (Request.QueryString["brand"]);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT * FROM Table_Products WHERE products_brand = #Pr_brand", conn);
cmd.Connection = conn;
cmd.Parameters.Add("#Pr_brand", System.Data.SqlDbType.VarChar).Value = Brand;
DataTable dt = new DataTable();
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows && reader.Read())
{
dt.Load(reader);
RepeaterBrand.DataSource = dt;
RepeaterBrand.DataBind();
}
conn.Close();
}
}
I'm quite new to C# so i might need some visual aid to get this.
Thank you in advance.
I hope this might help anyone this is what i ended up with after JaydipJ showed me the syntax.
if (Request.QueryString["brand"] != null && !IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
var Brand = (Request.QueryString["brand"]);
cmd.CommandText = "SELECT * FROM Table_Products WHERE products_brand = #Pr_brand";
cmd.Parameters.Add("#Pr_brand", System.Data.SqlDbType.VarChar).Value = Brand;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
RepeaterBrand.DataSource = dt;
RepeaterBrand.DataBind();
Don't read data from SQLDataReader. use it as it is to fill DataTable
if (reader.HasRows )
{
dt.Load(reader);
RepeaterBrand.DataSource = dt;
RepeaterBrand.DataBind();
}
Try This Code It's Working.
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select Mst_Emp_Login.Emp_Uname from Mst_Emp_Login", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
Repeater1.DataSource = ds;
Repeater1.DataBind();
ds.Dispose();adp.Dispose();
cmd.Dispose();
con.Close();con.Dispose();
}
catch(Exception err)
{
throw err;
}
Related
I have dropdownlist filled by database. how can I make it searchable?
I can do it with some issues but when data bind with database in note working.
is my filling method wrong?
<asp:Label ID="lbProbType" runat="server" Text="Problem Type""
Font-Bold="True"></asp:Label>
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(#"");
string readnamesquery = "select cwFullTitle from tbCowWorkers order by cwLName";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dpCaller.DataSource = dt;
dpCaller.DataTextField = "cwFullTitle";
dpCaller.DataBind();
cn.Close();
}
I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}
What is the problem with the following code? The GridView GridView1 does not show up on page at all.
public void display_range_mark()
{
int from = int.Parse(ddl_from_mark.SelectedValue.ToString());
int to = int.Parse(ddl_to_mark.SelectedIndex.ToString());
DataTable dt=Data.DoSomthing(string.Format("select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>='{0}' AND tn.NomreAdad<='{1}' AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars",from,to));
//DataTable data = Data.DoSomthing(string.Format("select t.Name,t.Id from tblStd t where t.DateSabt='{0}'", p.GetYear(DateTime.Now)));
GridView1.DataSource = dt;
GridView1.HeaderRow.Cells[0].Text = "نام";
GridView1.HeaderRow.Cells[1].Text = "نام خانوادگی";
GridView1.HeaderRow.Cells[2].Text = "شماره دانش آموزی";
GridView1.HeaderRow.Cells[3].Text = "درس";
GridView1.HeaderRow.Cells[4].Text = "نمره";
GridView1.DataBind();
}
I am getting this error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
The error occurs at this line:
GridView1.HeaderRow.Cells[0].Text = "نام";
By the way, the code for Data.DoSomthing is as folllows (It is located within class Database):
SqlConnection sc = new SqlConnection(#"Data Source=.;Initial Catalog=School;Integrated Security=True");
public DataTable DoSomthing(string text)
{
sc.Open();
DataTable data = new DataTable();
try
{
SqlCommand command = new SqlCommand();
command.Connection = sc;
command.CommandType = CommandType.Text;
command.CommandText = text;
SqlDataAdapter sd = new SqlDataAdapter(command);
sd.Fill(data);
if (data.Rows.Count == 0)
data = null;
}
catch (Exception ex)
{
sc.Close();
return null;
}
finally
{
if (sc.State != ConnectionState.Closed)
{
sc.Close();
}
}
return data;
}
Where is the connection object to connect to the database and fetch values ?
The way to do this:
string query="select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>=#from AND tn.NomreAdad<=#to AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars";
//Create Sqlconnection object
using(SqlConnection con = new SqlConnection(connectionstring))
{
//open the connection
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, con);
//To avoid sql injection using parameters
sda.Paramaters.AddWithValue("#from",from);
sda.Paramaters.AddWithValue("#to",to);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
I have two drop down list in which i am getting data displayed from database.
When College Name in DropDownList2 is selected only related branches must be shown in of that college in DropDownList1 for this i had used a Stored Procedure and it was working fine when i run it in manually by passing Parameteres.
But while executing code i all branches are displayed.do i need have any Post Back ?
Please help me in this scenario.
Below is my code:
string queryString = "select College_Name from Colleges";
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlConnection connection = new SqlConnection(constring);
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "College_Name";
DropDownList2.DataValueField = "College_Name";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
SqlCommand Cmd = new SqlCommand("Branch_display", connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add(new SqlParameter("#College_Name", DropDownList2.SelectedValue));
DataTable dt1 = new DataTable();
SqlDataAdapter ad1 = new SqlDataAdapter(Cmd);
ad1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
DropDownList1.DataSource = dt1;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
yes you need to have a post back somethink like this should help
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string queryString = "select College_Name from Colleges";
string constring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlConnection connection = new SqlConnection(constring);
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "College_Name";
DropDownList2.DataValueField = "College_Name";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
}
asp.net render
<asp:dropdownlist ID=" DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged=" DropDownList2_SelectedIndexChanged">
and action
private void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
string constring=System.Configuration.ConfigurationManager.ConnectionStrings["ConnDBForum"].ConnectionString;
SqlCommand Cmd = new SqlCommand("Branch_display", connection);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add(new SqlParameter("#College_Name", DropDownList2.SelectedValue));
DataTable dt1 = new DataTable();
SqlDataAdapter ad1 = new SqlDataAdapter(Cmd);
ad1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
DropDownList1.DataSource = dt1;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));
}
connection.Close();
}
I have a main form (formMain) which loads a user control (classification) in its load event. And in the load event of the user control classification it displays a datagridview. Let me show you the code.
CLASSIFICATION
string serverstring = "user id = root; password=; server=localhost; database=purchase_order; connection timeout=3;";
private void load_data()
{
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
Luckily it's working but when I click the search button located in another user control (search) it raises an event in the main form (formMain) wherein it must FILTER the datagridview in the user control (classification) but my code is not working.
Maybe I have a syntax error in my string query. Here is the code.
MAIN FORM
void SearchClicked(object sender, EventArgs e)
{
Search content = _searchbox;
classification control = new classification();
MySqlConnection con = new MySqlConnection(serverstring);
try
{
string query = "SELECT * FROM tblclassification WHERE class_name LIKE '%#search'";
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
//MessageBox.Show(content.txtboxSearch.Text);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
DataTable dt = new DataTable();
da.Fill(dt);
control.dataGridView1.DataSource = dt;
control.dataGridView1.DataMember = dt.TableName;
}
catch (Exception)
{
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
use CONCAT()
string query = #"SELECT *
FROM tblclassification
WHERE class_name LIKE CONCAT('%', #search)";
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("#search", content.txtboxSearch.Text);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
try
"SELECT * FROM purchase_order.tblclassification WHERE class_name LIKE ('%#search%')";
or ..
"SELECT * FROM tblclassification WHERE (class_name LIKE '%#search%')"