Hi vrindavani,
Check this example. Now please take its reference and correct your code.
HTML
<asp:DropDownList ID="drptype" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drptype_OnSelectedIndexChanged">
<asp:ListItem Text="A1">A1</asp:ListItem>
<asp:ListItem Text="B1">B1</asp:ListItem>
</asp:DropDownList>
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void drptype_OnSelectedIndexChanged(object sender, EventArgs e)
{
string type = drptype.SelectedValue;
string query = "";
if (type == "A1")
{
query= "INSERT INTO TableA (id,title,img,paragraph) VALUES(@Id,@Title,@Img,@Paragraph)";
}
if (type == "B1")
{
query = "INSERT INTO TableB (id,title,img,paragraph) VALUES(@Id,@Title,@Img,@Paragraph)";
}
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Parameters.AddWithValue("@Id", txtId.Text);
cmd.Parameters.AddWithValue("@Title", txtTitle.Text);
cmd.Parameters.AddWithValue("@Img", txtImage.Text);
cmd.Parameters.AddWithValue("@Paragraph", txtParagraph.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
VB.Net
Protected Sub drptype_OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim type As String = drptype.SelectedValue
Dim query As String = ""
If type = "A1" Then
query = "INSERT INTO TableA (id,title,img,paragraph) VALUES(@Id,@Title,@Img,@Paragraph)"
End If
If type = "B1" Then
query = "INSERT INTO TableB (id,title,img,paragraph) VALUES(@Id,@Title,@Img,@Paragraph)"
End If
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(query)
cmd.Parameters.AddWithValue("@Id", txtId.Text)
cmd.Parameters.AddWithValue("@Title", txtTitle.Text)
cmd.Parameters.AddWithValue("@Img", txtImage.Text)
cmd.Parameters.AddWithValue("@Paragraph", txtParagraph.Text)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Sub