Insert Command in a Gridview - asp.net

I am trying to execute an "INSERT INTO" command by using the asp:SqlDataSource InsertCommand in a C# statement ".Insert()".
The Button, "btninsert", resides in the header field of a gridview as does the inserting Textboxes: "TextBoxHeadercol1", "TextBoxHeadercol2" and "TextBoxHeadercol3".
I have 4 columns in my table, "test", they are "idt", "col1", "col2", "col3". My Gridview is "gvtotal".
I know that col1, col2 and col3 will print no data because I left out ItemTemplate with the labels.
public void btninsert_Click(object sender, EventArgs e)
{
SqlDataSource1.InsertParameters["col1"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol1")).Text;
SqlDataSource1.InsertParameters["col2"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol2")).Text;
SqlDataSource1.InsertParameters["col3"].DefaultValue = ((TextBox)gvtotal.HeaderRow.FindControl("TextBoxHeadercol3")).Text;
SqlDataSource1.Insert();
}
<asp:GridView ID="gvtotal"
runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="False"
DataKeyNames="idt">
<Columns>
<asp:BoundField DataField="idt" HeaderText="idt" Readonly="true" SortExpression="idt" />
<asp:TemplateField SortExpression="col1">
<HeaderTemplate>
<asp:TextBox ID="TextBoxHeadercol1" text="col1" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col2">
<HeaderTemplate>
<asp:TextBox ID="TextBoxHeadercol2" text="col2" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="col3">
<HeaderTemplate>
<asp:TextBox ID="TextBoxHeadercol3" text="col3" runat="server" MaxLength="40" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Button ID="btninsert" runat="server" Text="Insert Into" OnClick="btninsert_Click" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource
id="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:connone %>"
SelectCommand="SELECT * FROM [test];"
InsertCommand="INSERT INTO [test] [col1],[col2],[col3] VALUES #col1,#col2,#col3;"
runat="server"
/>

I think you might get away with this by using InsertCommand template provided by SQLDataSource. Write this command for SQLDataSource for
InsertCommand = "INSERT INTO Test(….) VALUES(#val1,#val2,#val3)
Use SQLDataSource template to map #val1, #val2 and #val3 to text boxes you want. The provided quick template will facilitate this. In the click event for Insert, simply refresh grid view view to display the new contents
public void btninsert_Click(object sender, EventArgs e)
{
gridview.DataBind();
}
Note that I do not have Visul Studio on my machine. Assume the above code as pseudo code

Related

Enabling /Disabling ButtonField of GridView using Checkbox

I have grid view
one column is ItemTemplate column which has Checkbox field.
Other 2 columns are Databound columns. One column is ButtonField which is of Button type.
I want this button to initially set to disabled mode
Once the Checkbox is checked it should be enabling that particular row button field. Could anyone help in this?
My sample try
.aspx file
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Button" />
</Columns>
</asp:GridView>
.aspx.cs file
protected void CheckBox2_CheckedChanged1(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gridrow = ((GridViewRow)(chk.Parent));
if (chk.Checked)
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = true;
}
else
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = false;
}
}
Try using the below code:
ASPX code for the GridView1:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind (for CheckBox Check Changed Event handler):
protected void CheckBox2_CheckedChanged1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView3.Rows)
{
((Button)row.FindControl("Button1")).Enabled = ((CheckBox)row.FindControl("non_prod_all_select")).Checked;
}
}
Changes made:
1.Set AutoPostBack for CheckBox to true.
2.Removed Button Field and added a template field with button in the third column of the Grid (so that the asp:Button control could be read easily in code behind)
3.Changed the code behind code to do the necessary.
NOTE: I have checked this code locally and is working as expected. So just replace your old code with this and let me know in case of any issues.

Get data from the row of a Dropdown in a Gridview

I have a Gridview with a column that has a DropDownList.
I've binded this Dropdownlist with an event on the "SelectedIndexChanged".
The problem is i can't get the value of a label of another column in the same row.
The code is the next:
protected void grid_OnSelectedIndexChanged(object sender, EventArgs e)
{
grdCredenciales.DataBind();
var dropdown = (DropDownList)sender;
var row = (GridViewRow)dropdown.NamingContainer;
var label = (Label)row.FindControl("lblMatricula");
var value = label.Text; // I get "" in this line.
}
And in the grid i have:
<asp:ObjectDataSource ID="CredencialesDS" runat="server" />
<asp:GridView ID="grdCredenciales" runat="server" BackColor="White" DataSourceID="CredencialesDS"
CssClass="DDGridView" RowStyle-CssClass="td" HeaderStyle-CssClass="th" CellPadding="6" AllowSorting="True"
AllowPaging="True" AutoGenerateColumns="False" PageSize="10" OnRowDataBound="grdCredenciales_OnRowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label7" ToolTip="Matrícula" runat="server" Text="Matrícula"/>
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblMatricula" runat="server"><%# Eval("Matricula") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label19" ToolTip="Estado" runat="server" Text="Estado" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Left" Width="15%"/>
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:DropDownList runat="server" ID="dpEstadoCredencial" AutoPostBack="True" OnSelectedIndexChanged="grid_OnSelectedIndexChanged" CssClass="comboEstado"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I don't know why, but label.text returns an empty string. As you can see, i am calling the DataBind before, so the label should have a value at this point.
Do you know how can i get the value i need from the label in another column?
Thanks for everyone.
Check the GridView's DataSource before you do the DataBind(). Since you're missing the full ASPX markup, I'm not sure if you're setting the data source programmatically or with a SqlDataSource.
In any case, what will happen often with programmatically-set Data Sources is that they disappear on a PostBack, and when you call that DataBind, you're really DataBinding it to null, which would explain why you're getting string.Empty ("") for the Label's Text property.
Just verified the code provided by you. It's working completely.
Please make sure in the RowDataBound event of Grid View, you reattach the dropdownlist's SelectedIndexChanged event as below:
protected void CustomersGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Page.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("dropdown1") as DropDownList;
if (ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(CustomersGridView_SelectedIndexChanged);
}
}
}
}
Also, I used the same code as yours in SelectedIndexChanged event. I'm putting here my aspx Markup:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
runat="server"
OnRowDataBound="CustomersGridView_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label2" Text='<%# Bind("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="dropdown1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="dropdown1_SelectedIndexChanged">
<asp:ListItem Text="Cat"></asp:ListItem>
<asp:ListItem Text="dog"></asp:ListItem>
<asp:ListItem Text="Mouse"></asp:ListItem>
<asp:ListItem Text="pig"></asp:ListItem>
<asp:ListItem Text="snake"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please provide your GridView markup too for checking.

Insert statement does not insert any data

I have a page where I display a list of groups for my application. There can be multiple users in a group. The group list is implemented with a gridview. Besides the column for the group description, the gridview has a button for adding users to it. When I click this button, the groupid is passed to a new page, on this page there is another gridview with a list of users. The gridview also has a buttonfield for adding that specific user to the group's group id. For this I have an extra table:
UserGroup
usergroupid
userid
groupid
My problem is, nothing is inserted into this table, the insert command is executed but something seems to be missing.
Here is my code:
Markup:
<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:GridView OnRowCommand="grdBenutzer_RowCommand" ID="grdBenutzer" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField ReadOnly="true" DataField="BenutzerID" HeaderText="ID" />
<asp:TemplateField HeaderText="Bezeichnung">
<ItemTemplate>
<%# Eval("Bezeichnung")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList AppendDataBoundItems="true" runat="server" ID="ddwnBezeichnung" Text='<%# Bind("Bezeichnung")%>'>
<asp:ListItem Text="Mitarbeiter" Value="Mitarbeiter"></asp:ListItem>
<asp:ListItem Text="Praktikant" Value="Praktikant"></asp:ListItem>
<asp:ListItem Text="Azubi" Value="Azubi"></asp:ListItem>
<asp:ListItem Text="Umschüler" Value="Umschüler"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vorname">
<ItemTemplate>
<%# Eval("Vorname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtVorname" Text='<%# Bind("Vorname")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nachname">
<ItemTemplate>
<%# Eval("Nachname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtNachname" Text='<%# Bind("Nachname")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="true" HeaderText="Geburtsdatum" DataField="Geburtsdatum" />
<asp:TemplateField HeaderText="Benutzerart">
<ItemTemplate>
<%# Eval("Benutzerart")%>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" HeaderText="Mitglied hinzufügen" Text="Mitglied hinzufügen" CommandName="MitgliedHinzufuegen" />
</Columns>
</asp:GridView>
<asp:SqlDataSource OnInserted="SqlDataSource1_Inserted" ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [BenutzerID], [Bezeichnung], [Vorname], [Geburtsdatum], [Nachname], [Benutzerart] FROM [Benutzer] WHERE [Archiviert] != 1"
InsertCommand="INSERT INTO BenutzerGruppe (BenutzerID, GruppenID) VALUES (#BenutzerID, #GruppenID)">
</asp:SqlDataSource>
</asp:Content>
Code-behind:
protected void SqlDataSource1_Inserted(object sender, SqlDataSourceStatusEventArgs e)
{
Response.Redirect("Gruppenverwaltung.aspx");
}
protected void grdBenutzer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MitgliedHinzufuegen")
{
string gruppenid = Request.QueryString["GruppenID"];
SqlDataSource1.InsertParameters.Add("GruppenID", gruppenid);
SqlDataSource1.Insert();
}
}
The inserted method fires after I add an user to the group, but when I view the group's members, no user was added....
The insert command expects input parameter #BenutzerID which you don't appear to be providing in the code-behind.

Gridview under Repeater control in asp.net

i have a repeater control which contains grids, based on values from database, say for example i have 2 grids inside repeater control, now both the grids contains a column which have up and down buttons, now when user clicks on the button from any grids, how can i check from which grid the button is called.
below is my code where i am filling the grids on RepeaterItemDataBound Event
GridView gvw = e.Item.FindControl("grid") as GridView;
gvw.DataSource = info.GetStories(sectionNames[e.Item.ItemIndex].Trim());
gvw.DataBind();
here section name contains the name of the sections, based on number of sections, i generate the grids.
My Design looks like this:
<asp:Repeater ID="rptGrids" runat="server"
OnItemDataBound="rptGrids_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="grid" runat="server" Width="100%" CellPadding="5" AllowPaging="true" ShowHeader="true" PageSize="10" AutoGenerateColumns="false" OnRowCommand="Stories_RowCommand">
<Columns>
<asp:BoundField DataField="ArticleID" HeaderText="Article ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="CategoryID" HeaderText="Category ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="Title" HeaderText = "Article Title" />
<asp:BoundField DataField="PublishDate" DataFormatString="{0:d}" HeaderText="Publish Date" ItemStyle-CssClass="center" />
<asp:TemplateField HeaderText="Select Action" ItemStyle-CssClass="center">
<ItemTemplate>
<asp:ImageButton ID="btnMoveUp" runat="server" ImageUrl="/images/up.gif" CommandArgument="Up" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnMoveDown" runat="server" ImageUrl="/images/dn.gif" CommandArgument="Down" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/deny.gif" CommandArgument="Delete" OnClientClick="return confirm('Are you sure you want to delete this article?');" CommandName='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="hdStoriesSortOrder" runat="server" Value='<%# Eval("SortOrder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="blank"></div>
</ItemTemplate>
</asp:Repeater>
this is my gridviews row_command event
protected void Stories_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandName.Split(',')[0]);
string section = e.CommandName.Split(',')[1].Trim().ToString();
string command = e.CommandArgument.ToString();
if (command.ToLower() == "up")
{
GridView grd = rptGrids.Items[1].FindControl("grid") as GridView; // If i specify the index here, i gets proper grid, but how to recognize at runtime.
Response.Write(grd.Rows.Count);
}
else if (command.ToLower() == "down")
{
}
}
can anyone tell me how can i get from which grid up/down button has been clicked.
You can use command argument to pass required value.
Here is sample of using imagebutton in similar way:
<asp:ImageButton ID="btnView" runat="server" ToolTip="<% $resources:AppResource,Edit %>"
SkinID="EditPage" CommandName="myCommand" CommandArgument='<%# Eval("CustomerId") %>'
PostBackUrl='<%# "~/AdminPages/Customer.aspx?id=" + Eval("CustomerId").ToString() %>' />
Take notice on CommandArgument property.You can set it with value that indicates specific gridview inside repeater.
And here is how to check the value:
protected void EntityGridViewContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
//here you can check for command name...
switch (e.CommandName)
{
case "myCommand":
//here you access command argument...
int customerId = Convert.ToInt32(e.CommandArgument.ToString());
break;
}
//here is how you access source gridview...
GridView gridView = (GridView)sender;
string controlId = gridView.ID;
}
You can also set CommandArgument using this approach:
CommandArgument='<%# GetMySpecialValue() %>'
Then you should declare function on page side something like this:
public string GetMySpecialValue()
{
return "some value";
}

ASP.NET inline ".FindControl()" in .aspx ListView?

In ASP.NET, we like using "child" SqlDataSource inside a bound grid server control (Girdview or ListView).
I've been using this FindControl() approach for years:
C# Codebehind:
protected void gridviewItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label labelItemId = (Label)e.Row.FindControl("labelItemId");
}
or like this:
protected void buttonSend_Click(object sender, EventArgs e)
{
Label labelItemId = (Label)((Control)sender).NamingContainer.FindControl("labelItemId");
}
Nothing wrong with it, but I'm quite tired of it and maybe there's a way to do this in .aspx markup?
Something like:
<asp:DropDownList
ID="dropdownItems"
runat="server"
DataSource=<% this.NamingContainer.FindControl("slqdatasourceItems") %>
DataTextField="ItemName"
DataValueField="ItemId" />
Is this possible?
I am not sure what your situation is. Do you have something like this?
namespace WebApplication1
{
public class Person
{
private string name;
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
public List<Person> GetAll()
{
List<Person> persons = new List<Person>();
Person p1 = new Person();
p1.Name = "John";
persons.Add(p1);
return persons;
}
}
}
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="dataGrid" AutoGenerateColumns="false" DataSourceID="persons">
<Columns>
<asp:BoundField HeaderText="Person Name" DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" DataTextField="Name" DataSourceID="persons"></asp:DropDownList>
<asp:ObjectDataSource runat="server" ID="persons" TypeName="WebApplication1.Person" SelectMethod="GetAll"></asp:ObjectDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource runat="server" ID="persons" TypeName="WebApplication1.Person" SelectMethod="GetAll"></asp:ObjectDataSource>
</div>
</form>
This is a web form with a gridview which has a "child" datasource pointing to the class Person and it´s method GetAll. There arise no problems at all. Please post some complete markup with your situation.
Edit
If you have something like this:
<asp:ListView runat="server" ID="lv" DataSourceID="SqlDataSource1">
<LayoutTemplate><div runat="server" id="itemPlaceholder"></div></LayoutTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Button runat="server" CommandName="Edit" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="Name" DataSourceID="SqlDataSource1"></asp:DropDownList>
<asp:SqlDataSource id="SqlDataSource1" runat="server" DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:SqlConnectionString%>" SelectCommand="SELECT Name FROM Person">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:ListView>
<asp:SqlDataSource id="SqlDataSource1" runat="server" DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:SqlConnectionString%>" SelectCommand="SELECT Name FROM Person">
</asp:SqlDataSource>
you shouldn´t have any problems either. I am here a assuming that you are drawing data from a table named "Person". Please show your special case as this is of course a simple setup.

Resources