Saving DATETIME datatype to MySQL - c#

I created a gridview in asp.net which has two columns of DATETIME datatype, when I connected to mysql database to save it within, it shows me an error " Incorrect datetime value: '01/01/2017 00:07:26' for column 'LogInDate_Time' at row 1" in cmd.ExecuteNonQuery(); line
How to solve it?
C#
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoggedIn(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedInDateTime = checkedRow.FindControl("lblLoggedInDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedInDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedInDateTime.Text = "";
}
}
protected void LoggedOut(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedOutDateTime = checkedRow.FindControl("lblLoggedOutDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedOutDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedOutDateTime.Text = "";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
string Attendance_ID = (row.FindControl("lblAttendanceID") as Label).Text;
string Attendance_Name = (row.FindControl("lblAttendanceName") as Label).Text;
string LogInDate_Time = (row.FindControl("lblLoggedInDateTime") as Label).Text;
string LogOutDate_Time = (row.FindControl("lblLoggedOutDateTime") as Label).Text;
InsertData(Attendance_ID, Attendance_Name, LogInDate_Time, LogOutDate_Time);
}
lblMessage.Text = "All Records Saved Successfully!!";
}
public void InsertData(string Attendance_ID, string Attendance_Name, string LogInDate_Time, string LogOutDate_Time)
{
//Your saving code.
string A = "server=localhost; userid=; password=; database=admindb; allowuservariables=True; Convert Zero Datetime=True; Allow Zero Datetime=True ";
using (MySqlConnection connection = new MySqlConnection(A))
{
string UpdateQuery = " INSERT INTO Attendance_Table (Attendance_ID, Attendance_Name,LogInDate_Time, LogOutDate_Time)" + " VALUES (#Attendance_ID,#Attendance_Name,#LogInDate_Time,#LogOutDate_Time)";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter paramAttendance_ID = new MySqlParameter("#Attendance_ID", Attendance_ID);
cmd.Parameters.Add(paramAttendance_ID);
MySqlParameter paramAttendance_Name = new MySqlParameter("#Attendance_Name", Attendance_Name);
cmd.Parameters.Add(paramAttendance_Name);
MySqlParameter paramLogInDate_Time = new MySqlParameter("#LogInDate_Time", LogInDate_Time);
cmd.Parameters.Add(paramLogInDate_Time);
MySqlParameter paramLogOutDate_Time = new MySqlParameter("#LogOutDate_Time", LogOutDate_Time);
cmd.Parameters.Add(paramLogOutDate_Time);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
ObjectDataSource1.InsertParameters["Attendance_ID"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtID")).Text;
ObjectDataSource1.InsertParameters["Attendance_Name"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtName")).Text;
ObjectDataSource1.InsertParameters["Attendance_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbAttendanceCon")).Text;
ObjectDataSource1.InsertParameters["LogInDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogIn")).Text;
ObjectDataSource1.InsertParameters["Leaving_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbLeavingCon")).Text;
ObjectDataSource1.InsertParameters["LogOutDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogOut")).Text;
ObjectDataSource1.Insert();
}
}

MySQL wants date in YYYY-MM-DD format.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/datetime.html

Related

How to do OnClick on selected item in "dynamic" ASP.NET DropDownList without using JavaScript

Currently, there is 2 values in my DropDownList which is viewProduct and editProduct. So when the user selects one of the value, it will direct user to the particular function in ASP.NET. I have tried OnSelectedIndexChanged, but it seems like not working on the dynamic DropDownList.
Here is my code:
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
if(ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if(ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
Any idea how to solve it without using JavaScript?
My entire code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT prodID, prodName, stockLevel, reorderLevel, unitPrice from Product";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
productList.DataSource = dt;
productList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
DropDownList ddlAction = new DropDownList();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Prod ID";
e.Row.Cells[1].Text = "Product Name";
e.Row.Cells[2].Text = "Qty";
e.Row.Cells[3].Text = "Reorder Level";
e.Row.Cells[4].Text = "Price (RM)";
e.Row.Controls.Add(tc);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var qty = Int16.Parse(e.Row.Cells[2].Text);
var reorder = Int16.Parse(e.Row.Cells[3].Text);
if (qty <= reorder)
{
e.Row.Cells[2].CssClass = "redCell";
e.Row.Cells[3].CssClass = "redCell";
}
e.Row.Controls.Add(tc);
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
if (ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if (ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
}
}
You need to declare an event handler then assign it to the control before adding the control to the page.
Here is an example :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CreateControl();
}
}
protected void CreateControl()
{
var ddlAction = new DropDownList();
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
e.Row.Cells[5].Controls.Add(ddlAction);
}
protected void DDLAction_OnSelectedIndexChanged(object sender, EventArgs e)
{
var action = (DropDownList) sender;
var choice = action.SelectedValue?.Trim();
string script = null;
switch (choice)
{
case "viewProduct":
script = "alert('View page!');";
break;
case "editProduct":
script = "alert('Edit page!');";
break;
default:
script = "alert('Unmatched Value!')";
break;
}
ScriptManager.RegisterStartupScript(this , typeof(_Default) , "TestJS" , $"<script>{script}</script>" , false);
}
use ScriptManager.RegisterStartupScript when you want to work with JS scripts. Response.Write will not parse script blocks as an executable blocks. It will throw a parse error though (you could check the browser console.

c# ado.net cant save long strings to sql database

I'm trying to get an input as text and save it to SQL table,
the code works fine if the string isn't too long, but when you exceed from about 70 characters the SaveChanges(); command isn't able to save the data.
SQL data type is set to nvarchar(max). Any idea?
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
this is the whole code in the solution :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Model.SAMA_User_CRM_V1 DB = new Model.SAMA_User_CRM_V1();
int IDGRID;
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnDELETE_Click(object sender, EventArgs e)
{
var qdel = DB.TBL_USERS.Where(x => x.ID == IDGRID).ToList();
foreach (var item in qdel)
{
DB.TBL_USERS.Remove(item);
}
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
IDGRID = (int)dataGridView1.Rows[e.RowIndex].Cells["ID"].Value;
}
}
}
considering the comments i found out where the problem is :
initially the model was created with a SQL table that used nvarchar(50) and after changing that to nvarchar(500) or nvarchar(max) the model.edmx needed to be updated ... after updating the model all things worked like a charm .

Auto suggest on gridview when typing on textbox

Can anyone help me on how can I do auto suggest on gridview when typing on textbox. Almost 1 week I seek for the solution. I already check my select statement, it connect to my database. And now I do not know why that coding is not function. Please somebody help me. This is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.IO;
namespace EmployeeVerification
{
public partial class Form1 : Form
{
//Connection String
string cs = "Server=..;User Id=sa;Password=..;Database=..";
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
//table to show in gridview
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from [GMT].[dbo].[m_employee] where not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
//make the textbox read only
textBoxICPass.ReadOnly = true;
textBoxPassport.ReadOnly = true;
textBoxDept.ReadOnly = true;
textBoxSection.ReadOnly = true;
pictureBox1.Visible = false;
dataGridView1.Visible = false;
textBoxEmplNo.CharacterCasing = CharacterCasing.Upper;
textBoxWorkNo.CharacterCasing = CharacterCasing.Upper;
textBoxName.CharacterCasing = CharacterCasing.Upper;
DataGridViewColumn column = dataGridView1.Columns[0];
column.Width = 300;
}
//auto suggest on gridview when typing on textbox
private void textBoxName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from m_employee where name like '%" + textBoxName.Text + "%' and not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
if (textBoxName.Text != null)
{
dataGridView1.Visible = true;
}
}
private void labelEmplNo_Click(object sender, EventArgs e)
{
}
private void textBoxEmplNo_TextChanged(object sender, EventArgs e)
{
}
private void textBoxWorkNo_TextChanged(object sender, EventArgs e)
{
}
private void labelTitle_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void buttonSelect_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBoxICPass_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
}
//show the row value in textbox
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
textBoxName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
textBoxEmplNo.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
textBoxWorkNo.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
textBoxICPass.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
textBoxPassport.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
textBoxDept.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
textBoxSection.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
dataGridView1.Visible = false;
}
//clear all the textbox fields after click
private void buttonClear_Click(object sender, EventArgs e)
{
foreach (Control crt in this.Controls)
{
if (crt.GetType() == typeof(TextBox))
crt.Text = "";
pictureBox1.Visible = false;
}
dataGridView1.Visible = false;
}
private void labelICPass_Click(object sender, EventArgs e)
{
}
private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxWorkNo.Text != "")
{
//Do something
string selectSql = "select name, empno, icnum, passport, deptno, section from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxEmplNo.Text = (read["empno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxEmplNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxWorkNo.Text + ".jpg";
if (File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
// MessageBox.Show("No Image Found");
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(#"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
}
}
}
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
string selectSql = "select name, workno, icnum, passport, deptno, section from m_employee where empno=#empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#empno", textBoxEmplNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxWorkNo.Text = (read["workno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxWorkNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg";
if(File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
MessageBox.Show("No Image Found");
}
}
}
}
}
Make these changes within your code:
You are setting dataGridView1.Visible = false; at various places within your code, remove all of them for instance, just for the sake of testing, you can add them later based on your requirements.
Remove this part of query where not [recsts] = 'R' order by empno" because for now it is useless and I don't understand why you are using this, you can apply filters later and also select ... from m_employee instead of [dbo]... etc..
Instead of dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); get data from selected row like this: textBoxName.Text = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString(); Because in future, if you increase/decrease the number of columns or re-arrange the order of getting data, it will not effect.
I've tested your code with these modifications and it works perfectly.

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

Populate gridview from dropdown control (C#)

I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();

Categories