Hi
If you are using C#, you can try something like the following:
Code Block
TreeViewP
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}
DataTable dt = new DataTable();
SqlConnection cn = new SqlConnection("Data Source=localhost;Initial Catalog=NorthWind;Integrated Security=True");
private void Form6_Load(object sender, EventArgs e)
{
SqlCommand cm = new SqlCommand("select categoryId,categoryName from Categories", cn);
SqlDataAdapter da = new SqlDataAdapter(cm);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
TreeNode tn = new TreeNode(dr["categoryName"].ToString());
tn.Tag = dr["categoryId"].ToString();
this.treeView1.Nodes.Add(tn);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{//add a Category item
SqlCommand insercommand = new SqlCommand("InsertCategory", cn);
insercommand.CommandType = CommandType.StoredProcedure;
insercommand.Parameters.Add("@CategoryName", SqlDbType.NVarChar,15).Value = this.textBox1.Text;
SqlParameter myParm = insercommand.Parameters.Add("@Identity", SqlDbType.Int);
myParm.Direction = ParameterDirection.Output;// use to retrieve the CategoryId
cn.Open();
try
{
insercommand.ExecuteNonQuery();
TreeNode tn = new TreeNode(this.textBox1.Text);
tn.Tag = myParm.Value.ToString();
this.treeView1.Nodes.Add(tn);
}
catch
{
MessageBox.Show("Save Data Error!");
}
finally
{
cn.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{//delete a Category item
string id = this.treeView1.SelectedNode.Tag.ToString();
SqlCommand deletecommand = new SqlCommand("delete Categories where categoryId = '" + id + "'", cn);
cn.Open();
try
{
deletecommand.ExecuteNonQuery();
this.treeView1.SelectedNode.Remove();
}
catch
{
MessageBox.Show("Delete Data Error!");
}
finally
{
cn.Close();
}
}
}
The InsertCategory stored procedure is like:
Code Block
CREATE PROCEDURE [dbo].[InsertCategory]
@CategoryName nvarchar(15),
@Identity int OUT
AS
INSERT INTO Categories (CategoryName) VALUES(@CategoryName)
SET @Identity = SCOPE_IDENTITY()
GO
Hope this helps. Best regards. Rong-Chun Zhang |