insert data into drisview and display in same gridview - c#

This is neither producing an error nor output. Help me out in this. Here my code is :
public partial class ScoHelpDesk : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
SqlDataAdapter adapt;
DataTable dt;
SqlConnection con2, con3;
SqlCommand cmd, cmd1, cmd2;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData_Sheet();
}
}
protected void InsertData1(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlserver"].ConnectionString);
TextBox t1 = (TextBox)GridView1.FooterRow.FindControl("TextBox2");
TextBox t2 = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
TextBox t3 = (TextBox)GridView1.FooterRow.FindControl("TextBox6");
TextBox t4 = (TextBox)GridView1.FooterRow.FindControl("TextBox8");
TextBox t5 = (TextBox)GridView1.FooterRow.FindControl("TextBox10");
TextBox t6 = (TextBox)GridView1.FooterRow.FindControl("TextBox12");
cmd = new SqlCommand("insert into tblHelpDesk (Name,Purpose,ContactNo,AlternativeNo,Email,Address) values(#Name,#Purpose,#ContactNo,#AlternativeNo,#Email,#Address)", con);
con.Open();
cmd.Parameters.AddWithValue("#Name", t1.Text);
cmd.Parameters.AddWithValue("#Purpose", t2.Text);
cmd.Parameters.AddWithValue("#ContactNo", t3.Text);
cmd.Parameters.AddWithValue("#AlternativeNo", t4.Text);
cmd.Parameters.AddWithValue("#Email", t5.Text);
cmd.Parameters.AddWithValue("#Address", t6.Text);
cmd.ExecuteNonQuery();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
catch (Exception ex)
{ }
}
private void BindData_Sheet()
{
DataTable dt = new DataTable();
using (SqlConnection con2 = new SqlConnection(con.ConnectionString))
{
string strQuery = "SELECT * FROM tblHelpDesk ";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}

Related

How to filter results in datagridview combobox based on combobox outside datagridview

I am trying to use the datagridview to input multiple data into sql, but I am having a hard time to bind the datagridview combobox to show items based on the selected item in the combobox (supplier), I can't even bind my sql in the datagridview combobox, sorry for being a noob, but I am trying to finish this project. the code below is the code that I use, it is based on individual comboboxes and textbox and not binded on datagridview.
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 Inventory.Properties;
namespace Inventory
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection(#"Data Source=MEDIXPC197;Initial Catalog=Inventory;Integrated Security=True");
SqlCommand cd = new SqlCommand();
private void label15_Click(object sender, EventArgs e)
{
}
private void Form2_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'inventoryDataSet.dbTrans' table. You can move, or remove it, as needed.
this.dbTransTableAdapter.Fill(this.inventoryDataSet.dbTrans);
cc();
cc2();
cc3();
}
public void cc()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Department from tbldept";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Department"].ToString());
comboBox2.Items.Add(dr["Department"].ToString());
}
conn.Close();
}
public void cc2()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select distinct Supplier from tblmaster";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["Supplier"].ToString());
}
conn.Close();
}
public void cc3()
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT [Transaction] from [tbltransac]";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox4.Items.Add(dr["Transaction"].ToString());
}
conn.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbldept where Department = '" + comboBox1.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbldept where Department = '" + comboBox2.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataReader dr = cmd.ExecuteReader();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach (DataRow dr in dt.Rows)
{
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [tbltransac] where [Transaction] = '" + comboBox4.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
conn.Close();
}
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where ProductCode = '" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
textBox3.Text = dr["Description"].ToString();
textBox4.Text = dr["UM"].ToString();
textBox5.Text = dr["UP"].ToString();
}
conn.Close();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
EDIT:
Picture below shows my design, I want to filter what will show in Item Code combobox inside the datagridview based on the Supplier combobox
PHOTO

filtering datagridview with combobox populated from same database

This is how my code really looks and performs. I have been trying to do filtering data according to comboboxes that I fill from the database and then to show data on the datagridview. Because I'm a beginner in coding, it has been really hard to write the combobox populating codes. I really searched in internet, read most of the titles. Is there any way to do this after all selections are done and maybe with the text is written in textbox and the search button (I created) clicked according to
the selections datagridview shows.
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;
namespace KPI_Tool
{
public partial class SearchForm : Form
{
static SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\010495\Desktop\KPI_Tool\KPI_Tool\KPI_Store.mdf;Integrated Security=True");
public SearchForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'kPI_StoreDataSet1.Store' table. You can move, or remove it, as needed.
this.myAdapter.Fill(this.myDataSet.Store);
}
private void Group_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox1.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT GroupN FROM Store WHERE GroupN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["GroupN"].ToString());
}
conn.Close();
}
private void Tech_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox2.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Tech_Area FROM Store WHERE Tech_Area IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox2.Items.Add(dr["Tech_Area"].ToString());
}
conn.Close();
}
private void Level_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox3.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT LevelOf FROM Store WHERE LevelOf IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["LevelOf"].ToString());
}
conn.Close();
}
private void Domain_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox4.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT DomainN FROM Store WHERE DomainN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox4.Items.Add(dr["DomainN"].ToString());
}
conn.Close();
}
private void Type_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox5.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT TypeN FROM Store WHERE TypeN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox5.Items.Add(dr["TypeN"].ToString());
}
conn.Close();
}
private void Severity_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox6.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Severity FROM Store WHERE Severity IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox6.Items.Add(dr["Severity"].ToString());
}
conn.Close();
}
private void AlertTB_Click(object sender, MouseEventArgs e)
{
AlertTB.Clear();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void ListB_Click(object sender, EventArgs e)
{
}
private void ClearB_Clicked(object sender, EventArgs e)
{
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
comboBox3.SelectedIndex = -1;
comboBox4.SelectedIndex = -1;
comboBox5.SelectedIndex = -1;
comboBox6.SelectedIndex = -1;
AlertTB.Clear();
AlertTB.Text = "Write Here..";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
myBindingSource.Filter = "GroupN= '{0}'"+comboBox1.SelectedItem.Te;
conn.Close();
}
}
}
Here is my User Interface. I'm using Visual Studio Professional 2013. Please explain to me with very basic sentences. I want to learn the logic, the structure behind the code.
If you want to filter the gridview according to the text you entered in the textbox you can refer to my blog post
http://dotnetsolutionsbyankit.blogspot.in/2013/04/filter-gridview-as-you-type-in-textbox.html
so you will get an idea how to do it.
If you face any problem let me know in comment.
public static DataSet SQLGetData(string connectionString, string commandString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Tables.Add(DT);
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
return DS;
}
}
private void SetFilter()
{
string command = "SELECT * FROM Store";
int count = 0;
if (comboBox1.Text != "")
{
command = command + " WHERE GroupN = '" + comboBox1.Text + "'";
count = count + 1;
}
if (comboBox2.Text != "")
{
if (count == 0)
{
command = command + " WHERE Tech_Area = '" + comboBox2.Text + "'";
}
else
{
command = command + " AND Tech_Area = '" + comboBox2.Text + "'";
}
count = count + 1;
}
if (comboBox3.Text != "")
{
if (count == 0)
{
command = command + " WHERE LevelOf = '" + comboBox3.Text + "'";
}
else
{
command = command + " AND LevelOf = '" + comboBox3.Text + "'";
}
count = count + 1;
}
// comboBox4, comboBox5, comboBox6
string connStr; //Connection string;
DataSet DS = new DataSet();
DS = SQLGetData(connStr, command);
DataGridView1.DataSource = DS.Tables[0];
}

facing an error with registration btn

When I fill the registration form and click on the button to move to user panel it does not move to the user panel, it freezes on the registration. In the user panel code behind it shows this message:
Object reference not set to an instance of an object.
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO UserInfo (UID, FN, LN, Password, RePass, Email,Country, State,City, Post, Img, Logo,RegDate) VALUES (#UID,#FN,#LN,#Password,#RePass,#Email,#Country,#State,#City,#Post,#Img,#Logo,#RegDate)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#UID", UsrNme.Text);
cmd.Parameters.AddWithValue("#FN", fnbox.Text);
cmd.Parameters.AddWithValue("#LN", lnamebox.Text);
cmd.Parameters.AddWithValue("#Password", passtxtbx1.Text);
cmd.Parameters.AddWithValue("#RePass", passtxtbx2.Text);
cmd.Parameters.AddWithValue("#Email", emailbox.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Post", postbox.Text);
cmd.Parameters.AddWithValue("#Img", persimgFileUpload1.FileName);
cmd.Parameters.AddWithValue("#Logo", logoFileUpload.FileName);
//Get the Current Date Time here
cmd.Parameters.AddWithValue("#RegDate", DateTime.Now);
if (!string.IsNullOrEmpty(UsrNme.Text))
{
Lblcheckusername.Text = "User Name Already Exist";
Lblcheckusername.ForeColor = System.Drawing.Color.Red;
}
else
{
Lblcheckusername.Text = "User Name Available";
Lblcheckusername.ForeColor = System.Drawing.Color.Green;
}
if (persimgFileUpload1.HasFile)
{
persimgFileUpload1.SaveAs(Server.MapPath("~/images/users/" + persimgFileUpload1.FileName));
}
if (logoFileUpload.HasFile)
{
logoFileUpload.SaveAs(Server.MapPath("~/images/Logos/" + logoFileUpload.FileName));
}
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
Here is the user panel codebehind where the error appears on the first code line:
USRNMElbl.Text = Session["UsrNme"].ToString();
if (Session["UsrNme"] != null)
{
}
if (!Page.IsPostBack)
{
DataTable countrycascd = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [countryID],[country] FROM [countr]", con);
adaptar.Fill(countrycascd);
countrdrdolst.DataSource = countrycascd;
countrdrdolst.DataTextField = "country";
countrdrdolst.DataValueField = "countryID";
countrdrdolst.DataBind();
}
countrdrdolst.Items.Insert(0, new ListItem("Välj land", "0"));
}
if (!Page.IsPostBack)
{
DataTable Sectiondt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
{
SqlDataAdapter adaptar = new SqlDataAdapter("select [CateID],[Category] FROM [Section]", con);
adaptar.Fill(Sectiondt);
Catedrdoads.DataSource = Sectiondt;
Catedrdoads.DataTextField = "Category";
Catedrdoads.DataValueField = "CateID";
Catedrdoads.DataBind();
}
Catedrdoads.Items.Insert(0, new ListItem("Select Section", "0"));
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1;
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 2;
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 3;
}
protected void addadsbtn_Click(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
SqlConnection cn = new SqlConnection(sc);
SqlCommand cmd = new SqlCommand();
string sqlstatment = "INSERT INTO [ads] ([Section], [Category], [UID], [AdsTit], [AdsDesc], [Country], [State], [City], [AdsPrice], [Img1], [img2], [img3], [img4], [img5], [Wtags]) VALUES (#Section, #Category, #UID, #AdsTit, #AdsDesc, #Country, #State, #City, #AdsPrice, #Img1, #img2, #img3, #img4, #img5, #Wtags)";
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sqlstatment;
//Insert the parameters first
cmd.Parameters.AddWithValue("#Section", Catedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#Category", SubCatedrdoads.SelectedItem.Text);
cmd.Parameters.AddWithValue("#UID", USRNMElbl.Text);
cmd.Parameters.AddWithValue("#AdsTit", addadstittxtbx.Text);
//cmd.Parameters.AddWithValue("#AdsDesc", Editor1.Text);
cmd.Parameters.AddWithValue("#Country", countrdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#State", statedrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#City", citiesdrdolst.SelectedItem.Text);
cmd.Parameters.AddWithValue("#AdsPrice", adsaddpristxtbx.Text);
cmd.Parameters.AddWithValue("#Img1", FileUpload1.FileName);
cmd.Parameters.AddWithValue("#Img2", FileUploadImg2.FileName);
cmd.Parameters.AddWithValue("#Img3", FileUploadImg3.FileName);
cmd.Parameters.AddWithValue("#Img4", FileUploadImg4.FileName);
cmd.Parameters.AddWithValue("#Img5", FileUploadImg5.FileName);
cmd.Parameters.AddWithValue("#Wtags", addadswtagtxtbtn.Text);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.SelectCommand = cmd;
ad.Fill(ds);
Response.Redirect("User panel.aspx");
}
The problem might be your Session["UsrNme"] is null
if (Session["UsrNme"] != null)
{
USRNMElbl.Text = Session["UsrNme"].ToString();
}
else
{
return;
}
You could also read http://www.codingdefined.com/2014/06/object-reference-not-set.html

data grid view no affected rows

I want to fill datagridview when rows affected=< 0 but i get error in line 47 gridview (id) = "correctgridview" runat = "server"
the first case work well but the error in the datagridview
mycode
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void insertButton_Click(object sender, EventArgs e)
{
int rowsaffected = 0;
dataset ds = new dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=attend; Integrated Security=true;");
SqlCommand cmd;
cn.Open();
cmd = new SqlCommand("atten", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter param = new SqlParameter();
param.ParameterName = "#myid";
param.Value = idTextBox.Text;
cmd.Parameters.Add(param);
rowsaffected = cmd.ExecuteNonQuery();
if (rowsaffected > 0)
{
resultLabel.Text = "added successful";
}
else
{
resultLabel.Text = "attend error";
SqlCommand command;
command = new SqlCommand("select id, courses.course , course_date , st_lec , location from courses inner join regestration on courses.course = regestration.course where id = 2", cn);
SqlDataAdapter adapte = new SqlDataAdapter(command);
DataTable Dt = new DataTable();
adapte.Fill(Dt);
correctGridView.DataSource = Dt;
correctGridView.DataBind();
}
cn.Close();
}
}

Populate datagridview by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in combobox. Now I want when I click on any of these table names from combo box that my DataGridView populates with that table's contents.
I have three tables in my database.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PopulateGridView(string tablename)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tablename;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
}
}
Here is my table (datejoin)
rahul sharma 12-1-2011
suresh chand 23-4-2012
prachi shukla 13-2-2011
siddharth malhotra 25-9-2012
saina chopra 12-8-2011
amit mehta 20-3-2012
Subscribe to the combobox's SelectedIndexChanged event and retrieve the selected table name from the combobox. From there, run a query to retrieve the records from the table and bind the result to the datagridview.
Sample:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
con.Open();
string tableName = comboBox1.SelectedText;
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tableName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dgv.DataSource = dtRecord;
con.Close();
}
You will have a event on combobox SelectedIndexChange and pass name of table to your function
private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
RebindGridView(ComboBox1.SelectedValue);
}
Then in your function:
private void RebindGridView(string tablename)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from " + tablename;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
gridview1.DataSource = dtRecords;
gridview1.DataBind();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources