Delete row in GridView using Two DataKeys in condition - asp.net

I want to delete a row in GridView and database as well.. I already have a stored procedure for the delete, the method is also created, but my problem is how can i use Two datakeys for my where clause. I've search and saw a lot of answers but they are using CommandArgument and that is applicable only in 1 datakeys.
I want something like this.
DELETE FROM TableName WHERE ID = Variable1 AND Name = Variable2
What i want is how can i retrieve the values of 2 datakeys in GridView if i set DataKeys like: DataKeys="ID, Name"
Any help would be appreciated.
Thanks

(if I correctly understood you)
stored procedure
Create Procedure [dbo].[Procedure_Name](
#Variable1 type(),
#Variable2 type() --you can add as many variables as you want, but then you have to add them in c# code as a parameters.
) as
delete from Table_Name
where Table_Name.Variable1 = #Variable1 AND Table_Name.Variable2 = #Variable2
with button in aspx code
<asp:Button ID="btnDeleteSomething" runat="server" Text="Delete Something" OnClick="btnDeleteSomething_Click"/>
then in c# codebehind
protected void btnDeleteSomething_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_NAME"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Procedure_Name", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
cmd.Parameters.Add("#Variable1", SqlDbType.VarChar, 70(its example with varchar)).Value = Variable1.Text(every Textbox, or label, or dropdownlist)
cmd.Parameters.Add("#Variable2", SqlDbType.Int).Value = Session["UserID]" - For example if u want do delete with parameter focused on user;
try
{
int rows = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
And it works fine without Datakeys at all. If u want to do it "with" then u have to add ControlParameter in your SqlDataSource. Hope it's going to help you.

Finally i found the solution on this link:
http://www.aspsnippets.com/Articles/Using-Multiple-DataKeyNames-DataKeys-in-ASPNet-GridView-with-examples.aspx
here is what exactly im looking for..
Dim rowIndex As Integer = TryCast(TryCast(sender, ImageButton).NamingContainer GridViewRow).RowIndex
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))`
Dim Name As String = GridView1.DataKeys(rowIndex).Values(1).ToString()`
Thanks

Related

dropdownList doesn't displays selected value

I am new at asp.net. I have a dropdownList which displays all categories for a specific article. The problem is that when I want to edit an article it doesn't displays the value that exists as default selected in dropdownList.
protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
SqlConnection con = new SqlConnection(connection);
string Qry = "select * from kategoria";
SqlDataAdapter da = new SqlDataAdapter(Qry, con);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds);
drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";
drpdKategoria.DataTextField = "emertimi";
drpdKategoria.DataBind();
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText(Qry).Value;
//drpdKategoria.Items.FindByValue(string val).Selected = true;
con.Close();
con.Dispose();
ds.Dispose();
da.Dispose();
}
}
EditArtikull.aspx
<asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
<fieldset>
<asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
</fieldset>
<br/>
ERROR:SystemNullReference Exception {"Object reference not set to an instance of an object."}
This line probably isn't going to find anything:
drpdKategoria.Items.FindByText(Qry)
Since Qry is a SQL statement:
string Qry = "select * from kategoria";
And I'm assuming that the display values in your DropDownList aren't SQL queries. Thus, when you call .Value on that first line, you're trying to de-reference something that isn't found (which is null), hence the error.
What item are you actually trying to find? If you want to select a default item, you need to be able to identify that item in some way. In your data that would be either by a known id value or a known emertimi value. For example, if you have a known emertimi value, it would be:
drpdKategoria.SelectedValue = drpdKategoria.Items.FindByText("some known value").Value
To make this a little more robust, you probably want to add some null checking. Something like this:
var defaultValue = drpdKategoria.Items.FindByText("some known value");
if (defaultValue != null)
drpdKategoria.SelectedValue = defaultValue.Value

why doesn't the c# update query for storedprocedure work?

This question arises out of a net article to insert and update a row of a GridView in a popup window. here.
Clicking on the edit button in GridView, you get a popup window for edit. You edit the window and click 'save' to save it in database. the save method is :
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
//cmd.CommandText = "AddUpdateCustomer";
cmd.CommandText = "UPDATE [Customers] SET [CompanyName] = #CompanyName ,[ContactName] = #ContactName WHERE CustomerID = #CustomerID";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#ContactName", txtContactName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtCompany.Text);
GridView1.DataSource = this.GetData(cmd);
GridView1.DataBind();
cmd.ExecuteNonQuery();
}
}
The online article used the commented line for cmd.CommandText which I changed as that did not work nor did I find its utility. I also added the last line cmd.ExecuteNonQuery(); to execute the query But actually no change in DB.
What might be wrong with the Save method and how to deal with that wrong ?
You've requested a call to a stored procedure, but the line you commented-out is the one that contains the stored procedure name.
It looks like you're actually executing raw SQL so you should try instead:
cmd.CommandType = CommandType.Text;
But your CommandText line won't work either because it isn't real SQL. It needs to include the content of the variables rather than the variable names. And also you should be executing a query rather than a non-query.
protected void Save(object sender, EventArgs e)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = String.Concat("UPDATE [Customers] SET [CompanyName] = ", txtCompany.Text, ", [ContactName] = ", txtContactName.Text, " WHERE CustomerID = ", txtCustomerId.Text, ";");
etc
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}
this is because on every postback asp.net will save the controls value in viewstate and when page return from server controlls are filled with old value and database table will update with old value rather than new value

C#/ASP.Net - Extract bit value of column in a gridview

I have a gridview that is SQL bound. In some of the columns there are bit values. When I use C# to get the values into the gridview, checkboxes are displayed. I need to extract the value of that column into text.
SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
{
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}
The gridview column data type is 'bit'. I do not have access to the database or stored procedure to change anything there. I need to somehow extract the '0' or '1' value, but when I do it like above, the text is blank.
I also tried to use 'GetOrdinal'. It returned a True/False value from the database, but I could not figure out how to get the value for each item in the gridview.
if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))
{
ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
}
General overview:
You need to be able to find the CheckBox that's generated and get the value of it's "Checked" property.
To do this, you need to be able to use the FindControl() method on the GridViewRow.
To use FindControl, the CheckBox needs a predictable name.
To get a predictable name, you need to have that column be a TemplateColumn so that you can specify the name of the CheckBox in the markup on the ASPX page.
There's a full working set of code here: http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater
This shows the code for a Repeater, but it's the same principle and general code for any DataBound control.
The code below should work with modifications to match your DB names:
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="MyColumnNameCheckbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
string defaultvalue = "0"; // To be used to display the value of the original bit field.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox");
if (chkBx != null && chkBx.Checked)
{
defaultvalue = "1";
}
}
I was able to figure it out. Thanks, David Stratton, for pointing me in the right direction.
I did it by assigning an id to the dynamically created control first. then did the FindControl()...
Control ctrl = GridView1.SelectedRow.Cells[4].Control[0];
ctrl.ID = "ctrl";
Boolean result = Convert.ToBoolean(((Checkbox)GridView1.Rows[0].Cells[4].FindControl("ctrl")).Checked);
TextBox1.Text = result.ToString();
This returns a value of "True" or "False"...
Thanks again.
Another way to resolve it:
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();
it resolve the problem with less code :)

Gridview filtering using textbox in asp.net

i want to know as how to search or filter records in a gridview dynamically based on the character(s) entered on a textbox. What is the best way to achieve this? Any sample codes or examples will be really helpful.
The trick here is to make databind only when the text change on the search box, but you must always set the datasource select command code. So you add a text box, and a button that say, submit, and you have the following:
OnPageLoad ->
if(SearchContron.Text.Length > 0)
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE WHERE Desc LIKE N'%" + SearchContron.Text +"%'"
else
SqlDataSource1.SelectCommand = "SELECT * FROM TABLE "
and
OnSubmitButtonClick -> GridView.DataBind()
If you do it other way, the paging and editing and other commands will fail. You can also make it more advanced if you get the text from the text box and break it in many words and search each one as separate on the same sql command.
Its simple,
Look here for a basic tutorial on adding Ajax control to page.
1) Add the text box as well as the grid view into same update panel
2) In the text box's key press event, you can set the data source of gird and invoke databind command.
Note that when the key press will be fired, it will cause the complete page life cycle to be executed at server side. Hence, you will have to check whether the post back is async or not in your Page Load even handler.
A trick to reduce the number of database queries being fired is to set a timer when the user presses a key with a timeout of say...500ms and do the databinding of gridview in timer's tick event. If you do this, database will be queried only when the user has stopped typing something.
Thanks,
Vamyip
To bind gridview data write the following code
private void GridData()
{
string conString = ConfigurationManager.ConnectionStrings["MyCon"].ToString();
SqlConnection sqlcon = new SqlConnection(conString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
String query;
if (txtsearch.Text == "")
{
query = "select PersonID,LastName,FirstName from Person";
}
else
{
query = "select PersonID,LastName,FirstName from Person where PersonID like '" + txtsearch.Text + "%' or LastName like '" + txtsearch.Text + "%' or FirstName like '" + txtsearch.Text + "%'";
}
sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
grdsearch.DataSource = dt;
grdsearch.DataBind();
}
else
{
grdsearch.DataBind();
Label1.Text = "No Records Found";
}
sqlcon.Close();
}
In page load event
if (!IsPostBack)
{
GridData();
}
for search button click event call GridData() method and
for clear button click event write following code
txtsearch.Text = "";
GridData();
Label1.Text = "";
Unless you have a specific need to do this on the server, why not perform the filtering on the client? A solution like DataTables is fast and user-friendly.
If you do other way to working search filtering condition for grid view header part. it is easy to use implement in your code. This is concepts used without database but i was using data table in linq. i hope to this code use full.
DataTable dt = (DataTable)Session["ProductTable"];
var query = from t in dt.AsEnumerable()
where t.Field<string>("ProducId").StartsWith(txtProductId.Text.ToString().Trim())
|| t.Field<string>("ProducId").Contains(txtProductId.Text.ToString().Trim())
select t;
Here is a sample program.
implement the onclick of search button like this:
protected void searchButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(searchTextBox.Text))
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
" ORDER BY [name], [id]";
}
else
{
SqlDataSource1.SelectCommand = "SELECT id,name,address, datetime FROM nirmaan.[seller] where id <>0" +
"and "+DropDownList1.SelectedValue+" LIKE '%" + searchTextBox.Text + "%' ORDER BY [name], [id]";
}
GridView1.DataBind();
}

Updating a DataTable?

Hey guys, I have an ASP.NET GridView bound to a DataView that contains a DataTable. I'm not using a DataAdapter.
I want to update a row in my DataTable, so I do this:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DataView dv = (DataView)Session["My_DataTable"];
DataTable dt = dv.Table;
int rowIndex = GridView1.Rows[e.RowIndex];
dt.Rows[rowIndex]["FirstName"] = thenewfirstname;
dt.Rows[rowIndex]["MI"] = thenewmi;
dt.Rows[rowIndex]["LastName"] =thenewlastname;
Session["My_DataTable"] = dv;
//Reset the edit index.
GridView1.EditIndex = -1;
//Bind data to the GridView control.
GridView1.DataSource = Session["My_DataTable"];
GridView1.DataBind();
}
The underlying DataView/DataTable is changed correctly, but the GridView contains both the old row before the edit, and the new row after the edit (that is, it adds an additional row with the new edits!).
For example, if we have :
...
Sammy S Samerson
...
and change it to Sammy E Samerson the gridview says :
...
Sammy S Samerson
Sammy E Samerson
...
How do I fix this, what did I do wrong?
A lot of strange things were happening.
The gist of all of the Bad Things was the DataView - because things were being reordered, the index of the GridView, and the index of the DataTable in the DataView weren't matching up. The DataTable had to be looped through untill the correct just-edited record was found.
Did you check the row index of the editing row. int rowIndex = GridView1.Rows[e.RowIndex]; you can directly use the e.RowIndex.
My Suggestion is to get the row by using any key field of the table.
for example
DataRow[] customerRow =
dataSet1.Tables["Customers"].Select("CustomerID = 'ALFKI'");
customerRow[0]["CompanyName"] = "Updated Company Name";
customerRow[0]["City"] = "Seattle";
You can get the row values by using the cell position. Or use datakeynames
for example :
string courseid = GridView1.Rows[e.RowIndex].Cells[3].Text;

Resources