get value into query from edit mode in gridview - asp.net

I have a simple gridview, 2 columns. The first column is a numeric value. The second column is based on a selected value from a drop down list. I have the drop down list working, but when I go to update the table, I get an error :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
The offending line is 55
Line 53: {
Line 54: string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
Line 55: string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
and here is the code behind for the webform:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string query = "select distinct Unit from vw_KmartBU";
SqlCommand cmd = new SqlCommand(query);
dlBU.DataSource = GetData(cmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
//dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string AnnoNum = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [Business Unit] = #BU where [Annotation Number] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnoNum);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindData()
{
string query = "select [Annotation Number], [Business Unit] as Unit from vw_GridviewSource";
SqlCommand cmd = new SqlCommand(query);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
}
What I need to do is get the value in first column "Annotation Number" and use it in the where clause of my update. So I would need update vw_GridviewSource set [Business Unit] = 'Accessories' where [Annotation Number] = '123456'
Accessories would have been the selection from the drop down list and 123456 would have been in the text box when I selected that row for editing.

Your gridview is missing DataKeyNames. It may look like:
<asp:GridView ID="gvSummary"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="AnnoNum, MyOtherKey1, MyOtherKey2"
... ... ...
DataKeyNames property is an array of strings. You can find more in MSDN

Related

asp.net grid view edit and delete records

i am trying to use a grid view to display items from the database i also want to edit and delete these records then in the grid view, i am using the sample code on asp.net snippets
http://aspsnippets.com/Articles/Simple-Insert-Select-Edit-Update-and-Delete-in-ASPNet-GridView-control.aspx
it says that The name 'GetData' does not exist in the current context
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default10 : System.Web.UI.Page
{
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
comm = new SqlCommand("select EmployeeID,Name,Password" +
" from Employee");
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "update Employee set Name=#Name," +
"Password=#Password where EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value = EmployeeID;
comm.Parameters.Add("#Name", SqlDbType.VarChar).Value = Name;
comm.Parameters.Add("#Password", SqlDbType.VarChar).Value = Password;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
protected void DeleteEmployee(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
comm = new SqlCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = "delete from Employee where " +
"EmployeeID=#EmployeeID;" +
"select EmployeeID,Name,Password from Employee";
comm.Parameters.Add("#EmployeeID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(comm);
GridView1.DataBind();
}
}
You are using Old coding so Replace your code with my code..
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default10 : System.Web.UI.Page
{
SqlCommand comm;
SqlConnection connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
connectionString.Open();
comm = new SqlCommand("select EmployeeID,Name,Password from Employee", connectionString);
DataTable dt =new DataTable();
SqlDataAdapter adp= new SqlDataAdapter(comm);
adp.Fill(dt);
connectionString.Close();
GridView1.DataSource =dt;
GridView1.DataBind();
}
protected void EditEmployee(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
//you should Write this code on Rowupdating and give command name 'update' to link button
protected void UpdateEmployee(object sender, GridViewUpdateEventArgs e)
{
//start here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtName")).Text;
string Password = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtPassword")).Text;
connectionString.Open();
comm = new SqlCommand("update Employee set Name=#Name,Password=#Password where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", EmployeeID);
comm.Parameters.AddWithValue("#Name", Name);
comm.Parameters.AddWithValue("#Password", Password);
comm.ExecuteNonQuery();
connectionString.Close();
GridView1.EditIndex = -1;
BindData();
//end here
}
//you should Write this code on RowDeleting and give command name 'delete' to link button
protected void DeleteEmployee(object sender, EventArgs e)
{
//stat here
string EmployeeID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblEmployeeID")).Text;
connectionString.Open();
comm = new SqlCommand("delete from Employee where EmployeeID=#EmployeeID", connectionString);
comm.Parameters.AddWithValue("#EmployeeID", lnkRemove);
comm.ExecuteNonQuery();
connectionString.Close();
BindData();
//end here
}
}

update a database from dataset

as you see in this code i was update the dataset ds at Button1_Click and i want to update the changes made on that dataset to the database.
if i wrote it at the Button1_Click it is work but when i put exactly the same code at Unnamed1_Click it is not working and i dont know why!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class Discount : System.Web.UI.Page
{
DataSet ds = new DataSet();
public void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9"))
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con); // יצירת dataAdapter
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int price;
for (int i = 0; i < GridView2.Rows.Count; i++)
{
if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
{
price = Convert.ToInt32(ds.Tables[0].Rows[i][2]);
price -= price * int.Parse(discountrate.Text) / 100;
ds.Tables[0].Rows[i][2] = Convert.ToString(price);
}
}
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
//SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_");
//con.Open();
//SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
//SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
//tmpda.Update(ds);
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098"))
{
con.Open();
SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
tmpda.Update(ds);
}
}
}
You need to specify the update command for your SqlDataAdapter. Just insert the following code after your commandBuilder instace:
tmpda.UpdateCommand = builder.GetUpdateCommand();

Object reference not set to an instance of an object while clicking on submit button

I have created a webpage in asp.net
on right hand side I have an ListBox which binds data from database when page loads, Its code at Default.aspx is as below
<asp:ListBox ID="ListOfSql" runat="server"
SelectionMode="Single" DataTextField="sql_name" DataValueField="sql_text"
style="margin-left: 0px; width:auto; height:300px" EnableViewState="true">
</asp:ListBox>
and at default.aspx.cs page its code is
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
I am calling loadSqlList() on page_load so that I can get list from database in ListBox.
Now I have an submit button
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
on default.aspx.cs page submit button's code is
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
Now when I want that on clicking on submit button then text of selected item should appear in textbox which is at left hand side
when I do so I am getting an error page
complete code of default.aspx.cs page is as below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
System.Data.OracleClient.OracleConnection conn = new OracleConnection("Data Source = orcl; user id=*****;password = *****; unicode = true;");
//OracleConnection conn = new OracleConnection("Data Source=orcl;Persist Security Info=True;User ID=system;password = ravi_123;Unicode=True");
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
loadSqlList();
lblLastRefresh.Text = DateTime.Now.ToShortTimeString();
lblDate.Text = DateTime.Now.ToShortDateString();
Response.Cache.SetAllowResponseInBrowserHistory(false);
//============================================= Checking user logged in or not ===================================
//if (Session["txtUserName"] == null)
//{
// Response.Write("<Script Language ='JavaScript'> alert('Session Expired, please login again')</script>");
// conn.Close();
// Response.Redirect("login.aspx");
//}
//============================================= Checking user logged in or not (END) ===================================
//=====================User Ip Tracer =======================
string UserIp = Request.ServerVariables["http_x_forwarded_for"];
string UserHost = Request.ServerVariables["http_X_forwarded_for"];
string userMacAdd = Request.ServerVariables["http_x_forwarde_for"];
if (string.IsNullOrEmpty(UserIp))
{
UserIp = Request.ServerVariables["Remote_ADDR"];
UserHost = System.Net.Dns.GetHostName();
}
LblLoc.Text = UserIp;
LblHostName.Text = UserHost;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Response.AddHeader("Pragma", "no-cache");
//=====================User Ip Tracer code end =======================
if (!IsPostBack)
{
}
}
protected void onclick_logout(object sender, EventArgs e)
{
conn.Close();
Session.Clear();
Response.Redirect("login.aspx");
}
protected void exportToExcel_Click(object sender, EventArgs e)
{
try
{
conn.Open();
string sql;
sql = txtQuery.Text.ToString();
OracleDataAdapter da = new OracleDataAdapter(sql, conn);
//================ User Details Data Insertion in DataBase Ends here ===============
da.Fill(dt);
ExportTableData(dt);
Response.Write("<Script>alert('Ip Locked in DB')</Script>");
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
protected void btnClear_clik(object sender, EventArgs e)
{
txtQuery.Text = string.Empty;
}
private void ExportTableData(DataTable dtdata)
{
string attach = "attachment;filename="+ListOfSql.SelectedItem.Text.ToString()+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attach);
Response.ContentType = "application/ms-excel";
if (dtdata != null)
{
foreach (DataColumn dc in dtdata.Columns)
{
Response.Write(dc.ColumnName + "\t");
}
Response.Write(System.Environment.NewLine);
foreach (DataRow dr in dtdata.Rows)
{
for (int i = 0; i < dtdata.Columns.Count; i++)
{
Response.Write(dr[i].ToString() + "\t");
}
Response.Write("\n");
}
Response.End();
}
}
// References for this page
// http://forums.asp.net/t/1768549.aspx
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
}
}
If a selection isn't made then ListOfSql.SelectedItem will be null, and therefore calling .Text on that will result in your error.
Try changing your code to something like this:
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
if(ListOfSql.SelectedItem != null)
{
txtQuery.Text = ListOfSql.SelectedItem.Text.ToString();
}
}

SQL Connection variable not in the current context

I am a beginner in.NEt and having difficulty using the sql connection in a radio button index changed eventhandler that i defined on the page_load.
Below is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Controls
{
public partial class Report_Selection : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.HeaderStyle.Font.Bold = true;
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
using (SqlConnection cnn = new SqlConnection("Data Source=DBSW9079;Initial Catalog=Underwriting;Integrated Security=SSPI;"))
{
SqlCommand cmd;
SqlDataReader sdr;
if (!IsPostBack)
{
cmd = new SqlCommand("select Categoryid,CategoryTitle from Report_Category", cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
SelectCategorydlist1.DataSource = sdr;
SelectCategorydlist1.DataTextField = "CategoryTitle";
SelectCategorydlist1.DataValueField = "categoryid";
SelectCategorydlist1.DataBind();
cnn.Close();
}
else
{
//It's a Post back
//make the grid visible and fill it
GridView1.Visible = true;
RadioButtonList1.SelectedValue = "1";
cmd = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description " + "where categoryid != 99999"
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr = cmd.ExecuteReader();
GridView1.DataSource = sdr;
GridView1.DataBind();
sdr.Close();
{
}
}
}
}
void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd1;
SqlDataReader sdr1;
if (RadioButtonList1.SelectedIndex.Equals(1))
{
RadioButtonList1.ClearSelection();
cmd1 = new SqlCommand("Select rptdesc,rptdesctext,categoryid from report_description "
+ "and categoryid = " + Convert.ToInt32(SelectCategorydlist1.SelectedValue).ToString(), cnn);
cnn.Open();
sdr1= cmd1.ExecuteReader();
GridView1.DataSource = sdr1;
GridView1.DataBind();
sdr1.Close();
}
}
}
}
In the above code when i use the cnn sequel connection in the event handler i get an small r
Your query in RadioButtonList1_SelectedIndexChanged appears to be incorrect. There's an and without a where:
Select rptdesc,rptdesctext,categoryid from report_description
and categoryid = ...
^^^ should be WHERE

Insert into table from two listbox controls

I have a requirement to insert user_id and quiz_iz into a table column, I have the below code which works for inserting multiple selected values from one control into a table column, but I cannot figure out how to insert in 2 fields from values listed on both controls when hitting Submit,.
I am using odbc connection to mysql, thats were the table i need to insert is located....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Odbc;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertRecords(StringCollection sc, StringCollection sc2)
{
string ConnectionString = #"driver={MySQL ODBC 5.1 Driver};server=localhost;database=db_mydb;uid=;pwd=;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
StringBuilder sb = new StringBuilder(string.Empty);
StringBuilder sb2 = new StringBuilder(string.Empty);
foreach (string item in sc)
{
const string sqlStatement = "INSERT INTO jos_jquarks_users_quizzes (quiz_id,user_id) VALUES";
sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
sb2.AppendFormat("{0}('{1}'); ", sqlStatement, item);
}
try
{
conn.Open();
OdbcCommand cmd = new OdbcCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
StringCollection sc = new StringCollection();
StringCollection sc2 = new StringCollection();
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
sc.Add(item.Text);
}
}
foreach (ListItem item in ListBox2.Items)
{
if (item.Selected)
{
sc2.Add(item.Text);
}
}
InsertRecords(sc , sc2);
}
}
You should use nested foreach maybe.
foreach (string item in sc)
{
foreach (string item in sc2)
{
insert sc and sc2
}
}

Resources