public DataTable getCats() { string selectQuery = "SELECT * FROM Category"; SqlCommand cmd = new SqlCommand(selectQuery); return FillDataTable(cmd); } public void add_Cat(string name,int? parentId) { SqlConnection con = new SqlConnection(connectionString); string insertQuery = "INSERT INTO Category VALUES(@name,@parentId)"; SqlCommand cmd = new SqlCommand(insertQuery,con); cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@parentId", (parentId.HasValue) ? parentId : (object)DBNull.Value); try { con.Open(); cmd.ExecuteNonQuery(); } finally { con.Close(); } } protected void btnSaveCat_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(txtCatName.Text)) return; int? parentId = null; if (ddlParentCat.SelectedIndex != 0) parentId = int.Parse(ddlParentCat.SelectedValue); DBUtil DB = new DBUtil(); DB.add_Cat(txtCatName.Text,parentId); bindToDDL(); } private void bindToDDL() { ddlParentCat.Items.Clear(); DBUtil DB = new DBUtil(); DataTable dt = new DataTable(); dt=DB.getCats(); displayCategory(dt,null,0); ddlParentCat.Items.Insert(0, new ListItem("Select a category", "0")); } private void displayCategory(DataTable dt, int? id, int depth) { foreach (DataRow row in dt.Rows) { if (row["Parent_id"].ToString() == id.ToString()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) sb.Append((char)0XA0); ListItem ls = new ListItem(sb + row["Cat_Name"].ToString(), row["Cat_id"].ToString()); if (depth == 0) ls.Attributes.Add("style", "color:red;"); ddlParentCat.Items.Add(ls); displayCategory(dt, int.Parse(row["Cat_id"].ToString()), depth + 1); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)