I am having a problem in selecting a value from dropdown list. Regardless of whatever I choose only the first value is selected always. Please help...
Here is the code...
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection con;
String strcon = ConfigurationManager.AppSettings["Constr"].ToString();
try
{
if (!IsPostBack)
{
con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select user_name from user_details where role='USER'", con);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataTextField = "user_name";
DropDownList1.DataSource = ds.Tables[0].DefaultView;
DropDownList1.DataBind();
}
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
protected void Button6_Click(object sender, EventArgs e)
{
string Name = Session["name"].ToString();
SqlConnection con;
String strcon = ConfigurationManager.AppSettings["Constr"].ToString();
try
{
con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select user_name,Arival,late,Day_count from attedance where user_name='" + DropDownList1.SelectedItem.Text + "' ", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
Don't quite get your code. You've shown two button click event handlers.
The first populates the drop-down, so the first item will be selected (that's how it works).
The second one populates a gridview.
If the issue arises from clicking 'Button4' (rename buttons to make it clear what they do), then that's your issue surely?
Also, you're not closing your SqlConnection. Use a using block:
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Do work here
}
EDIT: Ah, just noticed the (!IsPostBack).
Is ViewState enabled for the drop-down?
Related
Is there a way to display data from the database into the textbox but every time you click NEXT new row displays. I have this code but it doesn't work like I want it to because it displays all data into a textbox and not one row at a time.
private void buttonNEXT_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection("data source = people.sqlite");
conn.Open();
SQLiteCommand com = new SQLiteCommand(conn);
com.CommandText = "SELECT id, name, surname FROM people;";
SQLiteDataReader reader = com.ExecuteReader();
while (reader.Read())
{
textBox1.Text += reader["id"].ToString();
textBox2.Text += reader["name"].ToString();
textBox3.Text += reader["surname"].ToString();
}
conn.Close();
}
If you want to have a Next and Previous button and don't want to use a BindingNavigator control on your form, you can use a DataSet to store data and an SQLiteDataAdapter to fill it.
So you can have a function to fill and return a data set:
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SQLiteConnectionconn = new SQLiteConnection(ConnectionString);
SQLiteDataAdapter da = new SQLiteDataAdapter ();
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
return ds;
}
Then you should keep its returns value to a global variable in your main function like FormLoad :
dataset ds; // global variable
int index = 0; // for loop over dataset
private void frm_Load(object sender, EventArgs e)
{
ds = GetDataSet("data source = people.sqlite","SELECT id, name, surname FROM people;");
}
And in your button click:
private void buttonNEXT_Click(object sender, EventArgs e)
{
textBox1.Text = ds.Tables["People"].Rows[i]["id"].ToString();
textBox2.Text = ds.Tables["People"].Rows[i]["name"].ToString();
textBox3.Text = ds.Tables["People"].Rows[i]["surname"].ToString();
i++;
}
Note: You should check for i variable value by each click, it should not be bigger than ds.Tables["People"].Rows.Count
Do the same for previous button if you want it also.
The problem lies that upon selection of the date in the dropdown it will give the count of the LAST selection, not the current.
I am a novice and the only thing I can think of is some type of postback issue? The gridview populates fine with the records selected by the DDL, so I just cant get my head around why the count that is rendered is the previous selection.
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e)
{
lblRecordCounter.Text = "";
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT (*) FROM gescdb" +
"WHERE ClassDate=" + ddlClassDate.Text, conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
GridRegistrants.DataSource = reader;
GridRegistrants.DataBind();
reader.Close();
}
catch
{
}
finally
{
conn.Close();
lblRecordCounter.Text = GridRegistrants.Rows.Count.ToString();
}
In your Page_Load method you do the same, right? You have to move that code into following block:
if (!IsPostBack){
//Your code is here
}
Your DropDownList:
<asp:DropDownList ID="ddlClassDate" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlClassDate_SelectedIndexChanged" />
Your code behind:
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
BindDDL();
BindGrid(ddlClassDate.SelectedValue);
}
}
protected void BindDDL(){
//Bind Your dropdownlist here
}
protected void BindGrid(string ddate){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["gescdb"].ConnectionString);
SqlCommand comm = new SqlCommand("select * from gescdb where ClassDate = #date", conn);
comm.Parameters.Add("#date", SqlDbType.VarChar).Value = ddate;
try
{
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
sda.Fill(ds);
GridRegistrants.DataSource = ds;
GridRegistrants.DataBind();
}
catch
{
//...
}
finally
{
conn.Close();
}
}
protected void ddlClassDate_SelectedIndexChanged(object sender, EventArgs e){
BindGrid(ddlClassDate.SelectedValue);
}
I have two dropdownlist, corresponding to the values,gridview should be displayed,,and below is code for it..But i am not getting What's the problem in it!!
protected void ddlstudents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlstudents.SelectedIndex > 0)
{
BindData();
}
}
private void BindData()
{
try
{
SQLiteConnection con = new SQLiteConnection("data source=C:\\ITS Database\\its.development.sqlite3");
string strquery = "select topics.name,course_coverages.progress from topics JOIN course_coverages on topics.id=course_coverages.topic_id where course_coverages.student_id=#studentid AND course_coverages.course_id=#courseid";
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.connection=con;
cmd = con.CreateCommand();
cmd.CommandText = strquery;
cmd.Parameters.AddWithValue("#studentid", ddlstudents.SelectedIndex);
cmd.Parameters.AddWithValue("#courseid", ddlcourse.SelectedValue);
SQLiteDataAdapter ada = new SQLiteDataAdapter(cmd.CommandText, con);
SQLiteCommandBuilder cbl = new SQLiteCommandBuilder(ada);
DataTable dt = new DataTable();
ada.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
catch (SQLiteException)
{
}
}
Any Help Would Be Appreciated!!
Thanks in Advance!!
Learn how to find the problem your self. if the gridview not showing correct data you can debug the application and find where it failed.
you have not given how you bind ddlstudents and ddlcourse , check the values you get for ddlstudents.SelectedIndex and ddlcourse.SelectedValue as you expected or not.
if values are correct, you can run the SQL statement on your database with above values and see the results.
If you really need to find the error, remove the try catch statement from your code,
If you catch the exception, do something with it. otherwise don't.
try this
protected void ddlstudents_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlstudents.SelectedIndex > 0)
{
BindData();
}
}
private void BindData()
{
try
{
SQLiteConnection con = new SQLiteConnection("data source=C:\\ITS Database\\its.development.sqlite3");
string strquery = "select topics.name,course_coverages.progress from topics JOIN course_coverages on topics.id=course_coverages.topic_id where course_coverages.student_id=#studentid AND course_coverages.course_id=#courseid";
con.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.connection=con;
cmd = con.CreateCommand();
cmd.CommandText = strquery;
cmd.Parameters.AddWithValue("#studentid", ddlstudents.SelectedValue);
cmd.Parameters.AddWithValue("#courseid", ddlcourse.SelectedValue);
SQLiteDataAdapter ada = new SQLiteDataAdapter(cmd.CommandText, con);
SQLiteCommandBuilder cbl = new SQLiteCommandBuilder(ada);
DataTable dt = new DataTable();
ada.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
catch (SQLiteException)
{
}
}
I am creating one application in C# in which I am using datetimepicker control. I have created a database in MS Access which contains one table with Date_Entry, Emp_No, Emp_Name, In_Time, Out_Time columns.
Now I want to retrieve these data in textbox by clicking date on datetimepicker control. This date is point the date in Date_Entry field of database and fetch the data according to that date.
How to do it?
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0,DataSource=C:\\Users\\jd\\Desktop\\Attendance.mdb");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Attendance_Details WHERE Date_Entry=" + dateTimePicker1.Value + "", conn);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Attendance_Details");
txtDate.Text = ds.Tables[0].Rows[0][0].ToString();
txtEmpNo.Text = ds.Tables[0].Rows[0][1].ToString();
txtEmpName.Text = ds.Tables[0].Rows[0][2].ToString();
txtInTime.Text = ds.Tables[0].Rows[0][3].ToString();
txtOutTime.Text = ds.Tables[0].Rows[0][4].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
There are some problems in above code. I have refined it. Now it will work.
Following Should be the code:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0,DataSource=C:\\Users\\jd\\Desktop\\Attendance.mdb");
con.open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Attendance_Details WHERE Date_Entry=#dtpDate", conn);
cmd.Parameters.Addwithvalue("#dtpDate", dateTimePicker1.Value);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
txtDate.Text = ds.Tables[0].Rows[0][0].ToString();
txtEmpNo.Text = ds.Tables[0].Rows[0][1].ToString();
txtEmpName.Text = ds.Tables[0].Rows[0][2].ToString();
txtInTime.Text = ds.Tables[0].Rows[0][3].ToString();
txtOutTime.Text = ds.Tables[0].Rows[0][4].ToString();
con.close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.close();
}
}
}
Hope Its helpful.
To answer your problem about the "Error 1 'System.Data.OleDb.OleDbParameterCollection' does not contain a definition for 'Addwithvalue' and no extension method 'Addwithvalue' accepting a first argument of type 'System.Data.OleDb.OleDbParameterCollection'"
...did you Google? https://www.google.nl/search?q=Addwithvalue It actually shows you what's wrong.
About selecting dates: read this. It can be tricky. Make sure you use the right syntax.
on my asp.net project, how can i refresh my gridview immediately after clicking my button.
my button has update codes.here is the codes;
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL = "UPDATE [bilgiler3] SET [HAM_FM] = ISNULL(MON,0)+ISNULL(TUE,0)+ISNULL(WED,0)+ISNULL(THU,0)+ISNULL(FRI,0)+ISNULL(SAT,0)+ISNULL(SUN,0) WHERE [DATE] BETWEEN #DATE1 AND #DATE2 AND WORK_TYPE='OUT'";
string connStr = WebConfigurationManager.ConnectionStrings["asgdb01ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = strSQL;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#DATE1", Convert.ToDateTime(TextBox1.Text));
comm.Parameters.AddWithValue("#DATE2", Convert.ToDateTime(TextBox2.Text));
try
{
conn.Open();
int i = comm.ExecuteNonQuery();
conn.Close();
if (i > 0)
{
Response.Write(" SUCCESS ");
}
else
{
Response.Write(" ERROR ! ");
}
}
catch (SqlException ex)
{
Response.Write(ex.ToString());
}
}
}
}
you maybe gonna say "you need to bind the data of your gridview" but i couldnt understand the method.
can you help me about it ?
thank you very much.
I would do the following:
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
SqlConnection sc = new SqlConnection("you connection string here Security=True");
private void loadData()
{
try
{
ds.Clear();
SqlCommand sCmd= new SqlCommand("Load your database", sc);
sda.SelectCommand = sCmd;
sda.Fill(ds, "sCmd");
datagrid.DataSource = ds.Tables["sCmd"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
something for c# beginners Youtube
Add this code on your button click
SqlConnection con = new SqlConnection("Connection string from web config");
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter("select * from EmployeeTable", con);
con.Open();
sda.Fill(ds ,"Data");
gridview1.datasource=ds.tables[0];
gridview1.DataBind();
private SqlConnection con;
private SqlConnectionStringBuilder str;
private void Form8_Load(object sender, EventArgs e)
{
loadData();
}
private void loadData()
{
str = new SqlConnectionStringBuilder();
str.Provider = "";
str.DataSource = #"source.accdb";
con = new SqlConnection(str.ConnectionString);
dataGridView1.DataSource = fillTable("Select* from yourTable");
}
private DataTable fillTable(string sql)
{
DataTable datatable = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(sql, con))
{
da.Fill(datatable);
}
return datatable;
}
then If you want to refresh the table you put the loaddata(); in the event button_Click hope this help,
DataBind your control on success.
if (i > 0)
{
yourGridView.DataSource=YourDataSource;
yourGridView.DataBind();
Response.Write(" SUCCESS ");
}