GridView Not showing when i delete the all rows from database table - c#

i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}

No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.

try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx

Related

System.Data.SqlClient.SqlException Convert

System.Data.SqlClient.SqlException: Conversion failed when converting
the varchar value 'System.Data.DataRowView' to data type int.
How to convert?
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Sklad.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter dt;
DataTable dtCategories = new DataTable();
DataTable dtSubCategories = new DataTable();
DataTable dtItems = new DataTable();
public FrmItems()
{
InitializeComponent();
dt = new SqlDataAdapter("SELECT * FROM Categories", conn);
dt.Fill(dtCategories);
CbxCat.DataSource = dtCategories;
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
// TODO: Tento řádek načte data do tabulky 'skladDataSet.Items'. Můžete jej přesunout nebo jej odstranit podle potřeby.
this.itemsTableAdapter.Fill(this.skladDataSet.Items);
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
dtSubCategories.Clear();
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
CbxSubcat.DataSource = dtSubCategories;
CbxSubcat.DisplayMember = "NameSubCat";
CbxSubcat.ValueMember = "SubCatId";
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
dtItems.Clear();
dt = new SqlDataAdapter("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
dt.Fill(dtItems);
dataGridViewItem.DataSource = dtItems;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmHlavniMenu menu = new FrmHlavniMenu();
menu.Show();
this.Hide();
}
}
You claim it is failing on the second line below?
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
If CatId is an INT then this will fail because of the apostrophes (') surrounding the value. And please use parameters:
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId = #CatId", conn);
dt.SelectCommand.Parameters.AddWithValue("#CatId", CbxCat.SelectedValue);
dt.Fill(dtSubCategories);
Secondly, what is the type of CbxCat.SelectedValue? If it returns a string then you will need to parse the value as an integer: int.Parse(CbxCat.SelectedValue)
But the exception suggests it is actually of type System.Data.DataRowView. In that case you need to access the the item property, for example, CbxCat.SelectedValue["CategoryId"]
See for more info on DataRowView:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datarowview.item?view=netframework-4.8#System_Data_DataRowView_Item_System_String_
I finally solved it this way. It took me a lot of effort, but it was worth it. Thank you all for your support and thank you very very much.
enter code here
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Stock.mdf;Integrated Security=True;Connect Timeout=30");
int CatId;
public FrmItems()
{
InitializeComponent();
refreshCat();
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
}
private void refreshCat()
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Categories", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
CbxCat.DataSource = dt;
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
if (CbxCat.SelectedValue.ToString() != null)
{
CatId = Convert.ToInt32(CbxCat.SelectedValue.ToString());
refreshSubcat(CatId);
}
}
private void refreshSubcat(int CatId)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Subcategories WHERE CatId=#CatId", conn);
cmd.Parameters.AddWithValue("CatId", CatId);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxSubcat.DisplayMember = "NameSubcat";
CbxSubcat.ValueMember = "SubcatId";
CbxSubcat.DataSource = dt;
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
dataGridViewItem.DataSource = dt;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmMainMenu menu = new FrmMainMenu();
menu.Show();
this.Hide();
}
}
enter code here

didn't update the dropdownlist changed value asp.net C#

I want to take the drop down list's selected value to update another drop down list. data binding is working. but the "ddl1"'s selected value not change when selecting an item. therefore "ddl1.SelectedValue" notworkin correctly
Please check this code & help me to correct it
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
DataTable dt = new DataTable();
comm.Fill(dt);
conn.Close();
ddl1.DataSource = dt;
ddl1.DataTextField = "title";
ddl1.DataValueField = "id";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
Label2.Text = ddl1.SelectedIndex.ToString();
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap2 = "select [id]+' - '+[title] as title, id from map where id !='"+ddl1.SelectedValue+"' order by id;";
SqlDataAdapter comm2 = new SqlDataAdapter(selectmap2, conn);
DataTable dt2 = new DataTable();
comm2.Fill(dt2);
ddl2.DataSource = dt2;
ddl2.DataTextField = "title";
ddl2.DataValueField = "id";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
}
ASPX:
<asp:DropDownList ID="ddl1" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="ddl1_SelectedIndexChanged"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Populateddl1();
}
}
private void Populateddl1()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
DataTable dt = new DataTable();
comm.Fill(dt);
conn.Close();
ddl1.DataSource = dt;
ddl1.DataTextField = "title";
ddl1.DataValueField = "id";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
//Write here for populating second dropdown code
}

Is there any Way to show Empty GridView On pageLoad event?

Hope You all Are Fine
Can any one help me kindly i have a grid view that fetch tha record from database but show all the previous data which i entered by the grid but now i want to show the all data which i entering till the pageload even called, when page load that should not show all the entered records.
Thanks in Advance
Here is my code behind work
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("select distinct T1.SlpCode,T1.SlpName,T3.StepId,T3.Descript from OSLP T1 left join OPR1 T2 on T1.SlpCode=T2.SlpCode right join OOST T3 on T3.StepId=t2.Step_Id ", connection);
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
If you want to keep the grid empty on page load event, then do not write the code to bind it on Page Load event, instead write the code on"Add Button" click event(if that's what you want).
For showing empty record Grid You can Use EmptyDataTemplate.
For more you can try this Link

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();
}
}

DropDownList Value won't change

When I select any value from the DropDownList, the first one gets selected.
The code's purpose is whenever I choose a value from the DropDownList the corresponding value from the database should be displayed in the TextBox.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable dt = new DataTable();
SqlCommand sqlCmd = new SqlCommand("SELECT SeminarNameE,TrainerName FROM SeminarData WHERE SeminarName='" + DropDownList1.SelectedItem.Value +"'", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
TextBox1.Text = dt.Rows[0]["SeminarNameE"].ToString();
TextBox2.Text = dt.Rows[0]["TrainerName"].ToString();
}
}
Replace your page load with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
}
It needs !Page.IsPostBack, because everytime you bind, you clear any selections. In this code, it binds on every page load. Adding !Page.IsPostback will ensure it binds only the first load.

Categories

Resources