I'm new ASP.NET developer and trying to update a row in a GridView. I have try many solution but it don't work. When I update a row, not error message but the update is not taken into account.
<asp:GridView ID="grd_quest" Visible = "False" runat="server" CellPadding="4"
DataSourceID="ERP_questionn" ForeColor="#333333" GridLines="None"
AutoGenerateColumns="False" DataKeyNames="QUE_id">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField DataField="QUE_id" HeaderText="ID" ReadOnly="True"
SortExpression="QUE_id" ItemStyle-Width="10%" />
<asp:BoundField DataField="QUE_libelle" HeaderText="Libelle"
SortExpression="QUE_libelle" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="ERP_questionn" runat="server"
ConnectionString="<%$ ConnectionStrings:ERPConnectionString %>"
SelectCommand=""
UpdateCommand=
"UPDATE [TR_QUESTION] SET [QUE_libelle] = #QUE_libelle WHERE [QUE_id] = #QUE_id">
<UpdateParameters>
<asp:Parameter Name="QUE_libelle" Type="String" />
<asp:Parameter Name="QUE_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
The select command is not written here because it changes in function of others list so I write the SelectCommand in C#.
I hope it's clear for you
[EDIT]
I had try an other solution with this in C# :
protected void grd_quest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
int id = Convert.ToInt32(grd_quest.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)grd_quest.Rows[e.RowIndex];
//TextBox txtname=(TextBox)gr.cell[].control[];
TextBox textadd = (TextBox)row.Cells[2].Controls[0];
//TextBox textadd = (TextBox)row.FindControl("txtadd");
//TextBox textc = (TextBox)row.FindControl("txtc");
grd_quest.EditIndex = -1;
sqlConnection1.Open();
//SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
SqlCommand cmd = new SqlCommand("UPDATE TR_QUESTION SET QUE_libelle = #p_libelle where QUE_id = #p_id ", sqlConnection1);
cmd.Parameters.AddWithValue("#p_id", id);
cmd.Parameters.AddWithValue("#p_libelle", textadd.Text);
cmd.ExecuteNonQuery();
sqlConnection1.Close();
grd_quest.DataBind();
}
But it does not work too, I have an error message who say that :
The data source 'ERP_questionn' does not support updating unless UpdateCommand is specified. I have try : UpdateCommand = "" but it does not work too
[EDIT new try ]
protected void grd_quest_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = grd_quest.DataKeys[e.RowIndex].Value.ToString();
string libelle = ((TextBox)grd_quest.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
ERP_questionn.UpdateParameters["QUE_id"].DefaultValue = id;
ERP_questionn.UpdateParameters["QUE_libelle"].DefaultValue = libelle;
ERP_questionn.Update();
//ERP_questionn.SelectCommand = DropDownList1.SelectedValue;
}
When I update a row, not error message but the update is not taken into account.
[EDIT]
Maybe that can help,to display my data in my gridView I did this :
protected void lst_facteur_SelectedIndexChanged(object sender, EventArgs e)
{
if (lst_pos.SelectedValue == "1")
{
ERP_questionn.SelectCommand = "select * FROM TR_QUESTION WHERE FAC_id =" + lst_facteur.SelectedValue + " AND QUE_ordreUsine IS NOT NULL";
}
else if (lst_pos.SelectedValue == "2")
{
ERP_questionn.SelectCommand = "select * FROM TR_QUESTION WHERE FAC_id =" + lst_facteur.SelectedValue + " AND QUE_ordreBureau IS NOT NULL";
}
grd_quest.DataBind();
grd_quest.Visible = true;
txt_question.Visible = true;
btn_add_question.Visible = true;
I have always the update problem...
"UPDATE [TR_QUESTION] SET [QUE_libelle] =? WHERE [QUE_id] =?"
As well as this, you have not set an update command event on the gridview.
onrowupdated="CustomersGridView_RowUpdated"
You have to set SelectCommand = "SELECT * FROM [TR_QUESTION]" in HTML Code also:
<asp:GridView ID="grd_quest" runat="server" AutoGenerateColumns="False" DataKeyNames="QUE_id" DataSourceID="ERP_questionn">
<Columns>
<asp:CommandField ShowEditButton="True" />
<asp:BoundField DataField="QUE_id" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="QUE_id" />
<asp:BoundField DataField="QUE_libelle" HeaderText="Libelle" SortExpression="QUE_libelle" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="ERP_questionn" runat="server"
ConnectionString="<%$ ConnectionStrings:ERPConnectionString %>"
SelectCommand = "SELECT * FROM [TR_QUESTION]"
UpdateCommand =
"UPDATE [TR_QUESTION] SET [QUE_libelle] = #QUE_libelle WHERE [QUE_id] = #QUE_id">
</asp:SqlDataSource>
Related
I am rather new to programming in general. I am creating an webpage where the user selects a process from a sql populated dropdown list. A grid view then populates with the corresponding results with checkboxes. The end user can select a checkbox and that should save the value 1 to the database so that I can retrieve the checked items for another grid view later. Unfortunately it is only populating zeros. How can i fix this?
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
if (checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 1);
cmd.ExecuteNonQuery();
con.Close();
}
else if(!checkBox1.Checked)
{
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", 0);
cmd.ExecuteNonQuery();
con.Close();
}
}
Tried the following code as suggested but I am still having the same issue. I have included my design and ASP code for further help.
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = #IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource2" ForeColor="#333333" GridLines="None" Height="377px" Width="764px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Select">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="FAST_Screen" HeaderText="FAST Screen" SortExpression="FAST_Screen">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Audit_Detail" HeaderText="Audit Detail" SortExpression="Audit_Detail">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:QMSAuditConnectionString %>" SelectCommand="SELECT [FAST Screen] AS FAST_Screen, [Audit Detail] AS Audit_Detail, [EPS Process] AS EPS_Process, [IsSelected] FROM [AuditChecklist$] WHERE ([EPS Process] = #EPS_Process)">
<SelectParameters>
<asp:ControlParameter ControlID="LstProcess" Name="EPS_Process" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Design
It seems you set the ThreeState property of CheckBox to true, so it must be changed to false.
It doesn't need write same codes twice only for one check condition.
CheckBox checkBox1 = (row.Cells[0].FindControl("CheckBox1") as CheckBox);
string updateData = "update AuditChecklist$ set IsSelected = :#IsSelected";
SqlConnection con = new SqlConnection(conString);
con.Open();
SqlCommand cmd = new SqlCommand(updateData, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#IsSelected", checkBox1.Checked ? 1 : 0);
cmd.ExecuteNonQuery();
con.Close();
Also it will be better if an update statement has any filter (using where clause).
I want to Update An Number of goals That a Player Scored so if he socred a goal I want to do an update for his number of goals...
I got an Error in my Code And I don't know how to fix it. Can anyone help me to fix it, please ?
My Code:
string connectionStr = #"Provider=Microsoft.Jet.OleDb.4.0;Data Source=|DataDirectory|\SoccerDataBase.mdb";
using (OleDbConnection sqlCon = new OleDbConnection(connectionStr))
{
sqlCon.Open();
string queryStr = "SELECT Achievement FROM SoccerAchievements WHERE UserID=#AchNums";
OleDbCommand sqlCmd = new OleDbCommand(queryStr, sqlCon);
sqlCmd.Parameters.AddWithValue("#AchNums", (SoccerTable.FooterRow.FindControl("AchNums") as TextBox).Text.Trim());
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
DataSet ds = new DataSet();
dataAdapt.Fill(ds, "SoccerAchievement");
DataRow row = ds.Tables["SoccerAchievement"].Rows[0];
int a = int.Parse(row[3].ToString());
a = a + int.Parse("#AchNums");
string query = "UPDATE SoccerAchievements SET Achievement= '" + a + "' WHERE UserID= #AchNums";
sqlCmd.ExecuteNonQuery();
}
My GridView HTML CODE:
<asp:GridView ID="SoccerTable" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="קוד שחקן" InsertVisible="False"
SortExpression="ID" />
<asp:BoundField DataField="Team" HeaderText="קבוצות" SortExpression="Team" />
<asp:BoundField DataField="Players" HeaderText="שחקנים"
SortExpression="Players" />
<asp:TemplateField HeaderText="הישגים">
<FooterTemplate>
<asp:TextBox ID="AchNums" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button class = "AddButton" ID="AddButton" runat="server" onclick="AddButton_Click" Text="עדכן" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
My Error: There is no row at position 0.
Image:
My Data SoccerAchievements
Image:
Please help me guys :)
Replace this
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(queryStr, sqlCon);
With
OleDbDataAdapter dataAdapt = new OleDbDataAdapter(sqlCmd);
However you may again face error at your int.parse code.please correct that as well.
I have this application which is suppose to search the sql database for a invoice number. I am using only a textbox, gridview and button. My sql query gives me the correct information when I use the query builder but when I run the application I get over 400 records in the gridview. I am a beginner and I am looking for suggestions and help to get the correct results.
My asp code
<asp:TextBox ID="txtInvoice" runat="server"></asp:TextBox>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="SiteID" HeaderText="Site ID" SortExpression="SiteID">
<ItemStyle HorizontalAlign="Center" width="100" />
</asp:BoundField>
<asp:BoundField DataField="SiteDescription" HeaderText="Site Description" SortExpression="SiteDescription">
<ItemStyle HorizontalAlign="Left" Wrap="False" width="100"/>
</asp:BoundField>
<asp:BoundField DataField="InvoiceDate" HeaderText="Invoice Date" SortExpression="InvoiceDate">
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="InvoiceNumber" HeaderText="Invoice Number" SortExpression="InvoiceNumber">
<HeaderStyle Wrap="True" />
<ItemStyle HorizontalAlign="Center" Width="75" />
</asp:BoundField>
<asp:BoundField DataField="VendorNumber" HeaderText="Vendor Number" SortExpression="VendorNumber">
<HeaderStyle Wrap="True" />
<ItemStyle HorizontalAlign="Center" Width="100" />
</asp:BoundField>
<asp:BoundField DataField="VendorName" HeaderText="Vendor Name" SortExpression="VendorName">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField ="ReceivedDate" HeaderText="Received Date" SortExpression="ReceivedDate">
<ItemStyle HorizontalAlign ="Center" />
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:OneSourceConnectionString %>" SelectCommand="SELECT DISTINCT a.SiteID, a.SiteDescription, po.InvoiceDate, po.InvoiceNumber, v.VendorNumber, v.VendorName, po.ReceivedDate FROM AdmSites AS a INNER JOIN PreTranslations AS pt ON a.SiteID = pt.SiteID INNER JOIN InvAdjustments AS i ON a.AdmSiteID = i.AdmSiteID INNER JOIN PurSitePurchaseOrderHeader AS po ON a.AdmSiteID = po.AdmSiteID INNER JOIN InvVendors AS v ON po.InvVendorID = v.InvVendorID WHERE (po.InvoiceNumber LIKE #InvoiceNumber + N'%')">
<SelectParameters>
<asp:Parameter Name="InvoiceNumber" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Code behind:
protected void btnSearch_Click(object sender, EventArgs e)
{
// Get connection to the database
string strConn = ConfigurationManager.ConnectionStrings["OneSourceConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
// Query OneSource Database to grab invoice number
SqlCommand cmd = new SqlCommand("SELECT DISTINCT a.SiteID, a.SiteDescription, po.InvoiceDate, po.InvoiceNumber, v.VendorNumber, v.VendorName, po.ReceivedDate"
+ " FROM AdmSites a, InvVendors v, PurSitePurchaseOrderHeader po, InvAdjustments i, PreTranslations pt"
+ " WHERE a.SiteID = pt.SiteID"
+ " AND a.AdmSiteID = i.AdmSiteID"
+ " AND a.AdmSiteID = po.AdmSiteID"
+ " AND v.InvVendorID = po.InvVendorID"
+ " AND i.InvoiceNumber = #txtInvoice", conn);
cmd.Parameters.AddWithValue("#txtInvoice", txtInvoice.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
gvSearch.DataSource = dt;
gvSearch.DataBind();
}
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
conn.Close();
}
}
in that your code
you are using both thing
1)SQL DATASOURCE
" SelectCommand="SELECT DISTINCT a.SiteID, a.SiteDescription, po.InvoiceDate, po.InvoiceNumber, v.VendorNumber, v.VendorName, po.ReceivedDate FROM AdmSites AS a INNER JOIN PreTranslations AS pt ON a.SiteID = pt.SiteID INNER JOIN InvAdjustments AS i ON a.AdmSiteID = i.AdmSiteID INNER JOIN PurSitePurchaseOrderHeader AS po ON a.AdmSiteID = po.AdmSiteID INNER JOIN InvVendors AS v ON po.InvVendorID = v.InvVendorID WHERE (po.InvoiceNumber LIKE #InvoiceNumber + N'%')">
2)SqlCommand
SqlCommand cmd = new SqlCommand("SELECT DISTINCT a.SiteID, a.SiteDescription, po.InvoiceDate, po.InvoiceNumber, v.VendorNumber, v.VendorName, po.ReceivedDate"
+ " FROM AdmSites a, InvVendors v, PurSitePurchaseOrderHeader po, InvAdjustments i, PreTranslations pt"
+ " WHERE a.SiteID = pt.SiteID"
+ " AND a.AdmSiteID = i.AdmSiteID"
+ " AND a.AdmSiteID = po.AdmSiteID"
+ " AND v.InvVendorID = po.InvVendorID"
+ " AND i.InvoiceNumber = #txtInvoice", conn);
Don't use both thing
use only one
I have a GridView linked to a SQL table. Table have unknown or variable number of columns. Both the number of columns and the names of the columns are variable. Is it possible, to setup a dynamic UpdateCommand in the sqlDataSource so that I can update every column? If yes; how?
Code I tried:
<asp:GridView ID="GridView1" AutoGenerateColumns="True" ShowHeaderWhenEmpty ="True" DataSourceID="UpdateSqlDataSource"
CssClass = "table" runat="server" AllowSorting="True" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="UpdateID" ShowFooter="True"
AutoGenerateDeleteButton="true" AutoGenerateSelectButton ="true" AutoGenerateEditButton="true">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
<asp:SqlDataSource ID ="UpdateSqlDataSource" runat ="server" ConnectionString="<%$ ConnectionStrings:MachineUpdateDataBaseConnectionString %>"
DeleteCommand="DELETE FROM [MachineUpdate] WHERE [UpdateID] = #UpdateID"
SelectCommand="SELECT * FROM [MachineUpdate]" UpdateCommand="UPDATE SET [MachineUpdate] = #MachineUpdate WHERE [UpdateID] = #UpdateID[*] = #* WHERE [UpdateID] = #UpdateID">
<DeleteParameters>
<asp:Parameter Name="UpdateID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
The UpdateCommand of your SqlDataSource is always static, to generate an dynamic update, your should do it by C# code handling the RowUpdating event of the GridView.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string sqlCommand = "UPDATE YourTable SET ";
foreach (DictionaryEntry item in e.NewValues)
{
// You will need to take care to not update PK, FK, etc
// You will need to handle DB restrictions
// You will need to handle DataTypes (eg: Not set a boolean in a Date column)
sqlCommand = sqlCommand + item.Key + " = " + item.Value + ",";
}
sqlCommand = sqlCommand.TrimEnd(','); // removes the last comma
foreach (DictionaryEntry de in e.Keys)
{
//Assuming that you will have just only one key
// You can get the Key in the GridView.DataKeyNames property as well
sqlCommand = sqlCommand + " WHERE " + de.Key.ToString() + " = " + de.Value.ToString();
}
GridView grd = (GridView)sender;
SqlDataSource ds = (SqlDataSource)grd.DataSourceObject;
ds.UpdateCommand = sqlCommand; // Modify the UpdateCommand of you SqlDataSource
}
Note: Update columns dynamically isn't a good idea, you will have more headache than benefits. But for simple scenarios, the above code could work.
I have a Gridview like this.
<asp:GridView ID="GridView1" runat="server"
Width="16px" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Horizontal" Height="16px" >
<AlternatingRowStyle BackColor="#F7F7F7" />
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<sortedascendingcellstyle backcolor="#F4F4FD" />
<sortedascendingheaderstyle backcolor="#5A4C9D" />
<sorteddescendingcellstyle backcolor="#D8D8F0" />
<sorteddescendingheaderstyle backcolor="#3E3277" />
<SortedAscendingCellStyle BackColor="#F4F4FD"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#5A4C9D"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#D8D8F0"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#3E3277"></SortedDescendingHeaderStyle>
</asp:GridView>
Programaticly, i adding a data source this Gridview.
protected void SendToGridview_Click(object sender, EventArgs e)
{
Calculate.Visible = true;
MV_Label.Visible = true;
RISK_Label.Visible = true;
string strQuery;
string ConnectionString = ConfigurationManager.ConnectionStrings["ora"].ConnectionString;
OracleConnection myConnection = new OracleConnection(ConnectionString);
strQuery = #"SELECT A.HESAP_NO, A.TEKLIF_NO1 || '/' || A.TEKLIF_NO2 AS TEKLIF, A.MUS_K_ISIM AS MUSTERI,
B.MARKA, C.SASI_NO, C.SASI_DURUM, D.TAS_MAR, NVL(RISK_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.URUN_SIRA_NO, C.SIRA_NO),0) AS RISK,
NVL(MV_SASI(A.TEKLIF_NO1, A.TEKLIF_NO2, C.SIRA_NO, C.URUN_SIRA_NO, SYSDATE),0) AS MV
FROM S_TEKLIF A, S_URUN B, S_URUN_DETAY C, KOC_KTMAR_PR D
WHERE A.TEKLIF_NO1 || A.TEKLIF_NO2 = B.TEKLIF_NO1 || B.TEKLIF_NO2
AND A.TEKLIF_NO1 || A.TEKLIF_NO2 = C.TEKLIF_NO1 || C.TEKLIF_NO2
AND B.SIRA_NO = C.URUN_SIRA_NO
AND B.DISTRIBUTOR = D.DIST_KOD
AND B.MARKA = D.MARKA_KOD
AND B.URUN_KOD = D.TAS_KOD ";
string param = "";
foreach (ListItem l in CheckBoxList1.Items)
{
if (l.Selected)
{
param += string.Format("'{0}'", l.Value);
param += ",";
}
}
param = param.Remove(param.Length - 1);
strQuery = strQuery + " AND A.HESAP_NO IN (" + param + ")";
OracleCommand myCommand = new OracleCommand(strQuery, myConnection);
myCommand.CommandType = System.Data.CommandType.Text;
myCommand.Connection = myConnection;
myCommand.CommandText = strQuery;
myConnection.Open();
OracleDataReader dr = myCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
GridView1.DataSource = dr;
GridView1.DataBind();
GridView1.Visible = true;
myConnection.Close();
}
This is my Gridview looks;
What i want is, i want to add checkboxes column after RISK column and MV column.
I mean, columns looks like, HESAP_NO, TEKLIF, MUSTERI, MARKA, SASI_NO, SASI_DURUM, TAS_MAR, RISK, (CheckBoxes), MV, (Checkboxes). Totaly should be 11 column.
And i want all checkboxes is checked as a default.
How can i do that?
I read this article, but in this article Gridview a normal data source. I adding programaticly.
You are going to have to switch AutoGenerated columns off and used defined ones instead:
<asp:GridView ID="GridView1" runat="server" Width="16px" BackColor="White"
BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Horizontal" Height="16px" AutoGenerateColumns="false">
<!-- put your style stuff here -->
<asp:BoundField HeaderText="Text" DataField="HESAP_NO" />
<asp:BoundField HeaderText="Text" DataField="TEKLIF" />
<asp:BoundField HeaderText="Text" DataField="MUSTERI" />
<asp:BoundField HeaderText="Text" DataField="MARKA" />
<asp:BoundField HeaderText="Text" DataField="SASI_NO" />
<asp:BoundField HeaderText="Text" DataField="SASI_DURAM" />
<asp:BoundField HeaderText="Text" DataField="TAS_MAR" />
<asp:BoundField HeaderText="Text" DataField="RISK" />
<asp:BoundField HeaderText="Text" DataField="Text" />
<asp:CheckBoxField DataField="NameCheckBoxField1" HeaderText="NameCheckBoxField1" />
<asp:BoundField HeaderText="Text" DataField="MV" />
<asp:CheckBoxField DataField="NameCheckBoxField2" HeaderText="NameCheckBoxField2" />
</asp:GridView>
You will also need to change your SQL to return two fields that the CheckBoxField can map to. Those fields should contain a bit field with true set for all cases. This will allow the data to be automatically bound to the CheckBoxField and checked by default.
EG:
SELECT
-- all our fields
'NameCheckBoxField1' = 0x1,
'NameCheckBoxField2' = 0x1
FROM
-- etc...